class - Go,在 struct 中如何引用当前对象(就像 java 和 c++ 中的这样)?

标签 class go this

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/

相关文章:

windows - 在Go中调用Windows API时如何获取Windows系统错误代码

function - 如何实现功能?

javascript - 这个 JS 单例模式如何/为什么工作?

go - 在 Go 模板中使用 {{}} 原始表达式

javascript - 如何传递函数作用域(而不是上下文)?

JavaScript this 关键字和上下文

python - 调用方法的最佳方式 - Python

python:类对象列表的问题:所有项目都相同

c# - 不相关的类是什么意思?

使用 Fluent NHibernate 设置类映射