// 基本结构体定义type Person struct{
Name string
Age int}// 创建结构体实例funcmain(){
p1 := Person{
Name:"张三",
Age:30,}// 匿名实例
p2 :=struct{
Name string
Age int}{
Name:"李四",
Age:25,}}
type Swimmer interface{Swim()string}type Person struct{
Name string}func(p Person)Swim()string{return fmt.Sprintf("%s正在游泳", p.Name)}funcmain(){var s Swimmer = Person{Name:"张三"}
fmt.Println(s.Swim())}
4.4 多态
4.4.1 接口多态
type Shape interface{Area()float64}type Rectangle struct{
Width, Height float64}type Circle struct{
Radius float64}func(r Rectangle)Area()float64{return r.Width * r.Height
}func(c Circle)Area()float64{return math.Pi * c.Radius * c.Radius
}funcPrintArea(s Shape){
fmt.Printf("面积:%.2f\n", s.Area())}funcmain(){
r := Rectangle{Width:5, Height:3}
c := Circle{Radius:4}PrintArea(r)// 多态调用PrintArea(c)}