英文:
Go, in struct how to reference current object (like this in java and c++)?
问题
在Go语言中,this(或者在Python中是self)是用来表示当前对象的指针。在上述代码中,可以使用shape来代替this,因为shape是指向当前对象的指针。
因此,在setAlive函数中,可以使用shape.isAlive = isAlive来设置isAlive的值。
英文:
What is go's this (or self in python) construct?
type Shape struct {
isAlive bool
}
func (shape *Shape) setAlive(isAlive bool) {
}
in the setAlive function how do I do this.isAlive = isAlive; ?
答案1
得分: 6
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)
英文:
Go's method declarations have a so called receiver in front of the method name.
In your example it's (shape *Shape).
When you call foo.setAlive(false) foo is passed as shape to setAlive.
So basically the following is syntactical sugar
func (shape *Shape) setAlive(isAlive bool) {
shape.isAlive = isAlive
}
foo.setAlive(false)
for
func setAlive(shape *Shape, isAlive bool) {
shape.isAlive = isAlive
}
setAlive(foo, false)
答案2
得分: 4
在你的例子中,shape 是接收器。你甚至可以这样写:
func (this *Shape) setAlive(isAlive bool) {
this.isAlive = isAlive
}
英文:
In your example, shape is the receiver. You could even write it like this:
func (this *Shape) setAlive(isAlive bool) {
this.isAlive = isAlive
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论