前置
package main
import ("fmt"
)
// 矩形结构体
type Rectangle struct {Length intWidth int
}
// 计算矩形面积
func (r *Rectangle) Area() int {return r.Length * r.Width
}
func main() {r := Rectangle{4, 2}// 调用 Area() 方法,计算面积fmt.Println(r.Area())
}
type Person struct {name stringage int
}type Stu struct {Personschool string
}func (p *Person) show() {fmt.Println(p.name+":{}", p.age)
}func main() {s := Stu{Person{"ydy", 19}, "nnu"}s.show()
}
type shape interface {Area() int
}
type Square struct {w int
}
type Rectangle struct {l, w int
}
func (s *Square) Area() int {return s.w * s.w
}
func (r *Rectangle) Area() int {return r.l * r.w
}
func main() {r := &Rectangle{10, 2}q := &Square{10}
// 创建一个 Shaper 类型的数组shapes := []shape{r, q}// 迭代数组上的每一个元素并调用 Area() 方法for n, _ := range shapes {fmt.Println("图形数据: ", shapes[n])fmt.Println("它的面积是: ", shapes[n].Area())}
}