Go: Need to set property but without pointer receiver?

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

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!}

huangapple
  • 本文由 发表于 2015年3月9日 02:41:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/28930381.html
匿名

发表评论

匿名网友

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

确定