英文:
Go: Need to set property but without pointer receiver?
问题
package main
import "fmt"
type MyClass struct{
data string
}
func (this MyClass) MyMethod() {
this.data = "Changed!"
}
func main() {
obj := MyClass{}
obj.MyMethod()
fmt.Println(obj)
}
我需要通过MyMethod()
方法来改变data
属性的值,但是我不能将接收者类型改为指针(func (this *MyClass)
),因为它必须满足一个接口,而该接口的接收者不是指针。有其他方法可以实现这个吗?
英文:
package main
import "fmt"
type MyClass struct{
data string
}
func (this MyClass) MyMethod() {
this.data = "Changed!"
}
func main() {
obj := MyClass{}
obj.MyMethod()
fmt.Println(obj)
}
I need that the data
property gets changed by MyMethod()
, but I cannot change the receiver type to pointer (func (this *MyClass)
) because it must satisfy an interface whose receiver is not a pointer, can this achieved some other way?
答案1
得分: 4
你需要使用指针接收器而不是值接收器:
func (this *MyClass) MyMethod() {
this.data = "Changed!"
}
在 play.golang.org 上查看你修改后的示例:
输出结果为:
{Changed!}
英文:
You need to use a pointer receiver, not a value receiver:
func (this *MyClass) MyMethod() {
this.data = "Changed!"
}
See your modified example in play.golang.org:
The output is:
{Changed!}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论