什么是 go 的this(或self在 python 中)構造?type Shape struct { isAlive bool}func (shape *Shape) setAlive(isAlive bool) {}在setAlive函數中我該怎么做this.isAlive = isAlive;?
2 回答

江戶川亂折騰
TA貢獻1851條經驗 獲得超5個贊
在您的示例中,shape是接收器。你甚至可以這樣寫:
func (this *Shape) setAlive(isAlive bool) {
this.isAlive = isAlive
}

神不在的星期二
TA貢獻1963條經驗 獲得超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)
- 2 回答
- 0 關注
- 234 瀏覽
添加回答
舉報
0/150
提交
取消