首页 > 解决方案 > 使用值接收器存储新值

问题描述

鉴于该方法具有指针接收器,因此存储新值是规范的。例如:

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包装?

标签: go

解决方案


不。

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

x:=myTime{}
x.ValueReceiverFunc()

相当于:

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

推荐阅读