Go 系列教程 —— 17. 方法

MDGSF ·
还记得上个课程中的结构体字段提升吗,下面代码使用会产生二义性,这个大家需要注意! ```go package main import ( "fmt" "math" ) type Rectangle struct { length int width int } type Circle struct { radius float64 } func (r Rectangle) Area() int { return r.length * r.width } func (c Circle) Area() float64 { return math.Pi * c.radius * c.radius } type Test struct { id int name string Circle Rectangle } func main() { r := Rectangle{ length: 10, width: 5, } fmt.Printf("Area of rectangle %d\n", r.Area()) c := Circle{ radius: 12, } fmt.Printf("Area of circle %f", c.Area()) var t Test t.id = 1000 t.name = "test" t.Circle = c t.Rectangle = r fmt.Println(t.Area()) } ``` 将会输出如下: ```go 48:15: ambiguous selector t.Area ```
#5