Go中的方法和接收器

huangapple go评论87阅读模式
英文:

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
}

huangapple
  • 本文由 发表于 2014年10月15日 05:20:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/26370524.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定