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;
?
In your example, shape
is the receiver. You could even write it like this:
func (this *Shape) setAlive(isAlive bool) {
this.isAlive = isAlive
}
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)