Go语言中如何引用当前对象(类似于Java和C++中的this)?

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

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
}

huangapple
  • 本文由 发表于 2013年3月5日 23:02:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/15227065.html
匿名

发表评论

匿名网友

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

确定