我正在努力學習圍棋。當我認為我了解什么是函數、如何使用它并希望進入接口時,我陷入了困境(來源 Go 博客)package mainimport "fmt"//define a Rectangle struct that has a length and a widthtype Rectangle struct { length, width int}//write a function Area that can apply to a Rectangle typefunc (r Rectangle) Area() int { return r.length * r.width}func main() { r := Rectangle{length:5, width:3} //define a new Rectangle instance with values for its properties fmt.Println("Rectangle details are: ",r) fmt.Println("Rectangle's area is: ", r.Area())}為什么我們有 func (r Rectangle) Area() int而沒有func Area(r Rectangle) int?有什么不同嗎?
3 回答

子衿沉夜
TA貢獻1828條經驗 獲得超3個贊
它是一種方法而不是函數。通常,您可以選擇您更喜歡使用的方法(盡管當您有多個函數都作用于同一類型的對象時,方法通常更有意義)。唯一需要注意的是,您只能使用帶有接口的方法。例如:
type Shape interface {
Area() int
}
type Rectangle struct {
...
}
func (r *Rectangle) Area() int {
...
}
在這種情況下,要滿足Shape接口,Area()必須是方法。擁有:
func Area(r *Rectangle) int {
...
}
不會滿足接口。
- 3 回答
- 0 關注
- 213 瀏覽
添加回答
舉報
0/150
提交
取消