英文:
Methods and receivers in Go
问题
我有困难理解Go语言中的方法和接收器。假设我们有以下代码:
package main
import ("fmt"; "math")
type Circle struct {
x, y, r float64
}
func (c *Circle) area() float64 {
return math.Pi * c.r * c.r
}
func main() {
c := Circle{0, 0, 5}
fmt.Println(c.area())
}
在area
函数的定义中,(c *Circle)
被称为接收器,在main
函数中,我们可以通过引用调用area
并传递c
,而不使用指针。我可以将代码编辑为以下形式,它的工作方式相同:
package main
import ("fmt"; "math")
type Circle struct {
x, y, r float64
}
func circleArea(c *Circle) float64 {
return math.Pi * c.r*c.r
}
func main() {
c := Circle{0, 0, 5}
fmt.Println(circleArea(&c))
}
现在,这只是两段代码之间的语法差异,还是在更深层次上存在一些结构上的不同?
英文:
I have problems understanding methods and receivers in Go. Let's say we have this code:
package main
import ("fmt"; "math")
type Circle struct {
x, y, r float64
}
func (c *Circle) area() float64 {
return math.Pi * c.r * c.r
}
func main() {
c := Circle{0, 0, 5}
fmt.Println(c.area())
}
(c *Circle)
in the definition of the area
function is said to be a receiver and in the main
we can call area and pass c
by reference without the use of pointers. I can edit the code to the following and it works the same way:
package main
import ("fmt"; "math")
type Circle struct {
x, y, r float64
}
func circleArea(c *Circle) float64 {
return math.Pi * c.r*c.r
}
func main() {
c := Circle{0, 0, 5}
fmt.Println(circleArea(&c))
}
Now is this just a syntactical difference between the two snippets of code or is there something structurally different going on on a deeper level?
答案1
得分: 6
这是要翻译的内容:
区别不仅仅在于语法。使用方法,你的圆形类型可以实现一个接口,但是函数却不能做到这一点:
type areaer interface {
area() float64
}
英文:
The difference isn't just syntax. With a method, your circle type could fulfill an interface, but the function doesn't let you do that:
type areaer interface {
area() float64
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论