使用价值接收器存储新价值



如果方法有指针接收器,则存储新值是规范的。例如:

type MyTime time.Time
func (mt *MyTime) Change(other time.Time) {
*mt = MyTime(other)
}

但是,如果没有指针接收器,是否有可能

type MyTime time.Time
func (mt MyTime) Change(other time.Time) {
// ???
}

也许使用reflectatomic包?

否。

当调用带有值接收器的方法时,将使用接收器的副本来调用该方法。对接收器进行的任何修改都将在该副本上进行。换句话说:

x:=myTime{}
x.ValueReceiverFunc()

相当于:

x:=myTime{}
y:=x
y.ValueReceiverFunc()

相关内容

最新更新