go 的 this
(或 python 中的 self
)构造是什么?
type Shape struct {
isAlive bool
}
func (shape *Shape) setAlive(isAlive bool) {
}
在 setAlive
函数中,我该怎么做 this.isAlive = isAlive;
?
最佳答案
Go 的方法声明在方法名前面有一个所谓的接收器。
在您的示例中,它是 (shape *Shape)
。
当您调用 foo.setAlive(false)
时,foo
作为 shape
传递给 setAlive
。
所以基本上下面是语法糖
func (shape *Shape) setAlive(isAlive bool) {
shape.isAlive = isAlive
}
foo.setAlive(false)
对于
func setAlive(shape *Shape, isAlive bool) {
shape.isAlive = isAlive
}
setAlive(foo, false)
关于class - Go,在 struct 中如何引用当前对象(就像 java 和 c++ 中的这样)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15227065/