前置

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())}
}
