我正在努力学习围棋。当我认为我了解函数是什么、如何使用它并希望进入界面时,我陷入了困境(来源 Go blog)
package main
import "fmt"
//define a Rectangle struct that has a length and a width
type Rectangle struct {
length, width int
}
//write a function Area that can apply to a Rectangle type
func (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
?有什么不同吗?
最佳答案
这意味着您的函数附加到一个类型。您可以为任何用户定义的类型执行此操作。区别在于调用函数的方式,而不是使用:
a := Area(r);
您将使用:
a := r.Area();
这也意味着如果你定义一个像这样的方法
func (r Rectangle) String() string
Rectangle
将自动实现 Stringer
,您将获得打印 Rectangle
的能力。
关于go - 为什么 go 函数的定义不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22313986/