go - 使用值接收器存储新值
问题描述
鉴于该方法具有指针接收器,因此存储新值是规范的。例如:
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) {
// ???
}
也许使用reflect
或atomic
包装?
解决方案
不。
当您使用值接收器调用方法时,将使用接收器的副本调用该方法。对接收器执行的任何修改都将在该副本上完成。换句话说:
x:=myTime{}
x.ValueReceiverFunc()
相当于:
x:=myTime{}
y:=x
y.ValueReceiverFunc()
推荐阅读
- docker - 当工作节点从 Docker Swarm 中的网络问题重新连接时,如何保持原始工作容器处于活动状态
- git - 拉入子模块,现在在子模块中有一个无关的提交
- r - 如何将图例添加到具有多个组的 ggplot 中,这些组在数据框中具有多列数据
- r - 如何根据每行可变数量的模式匹配将行分成列
- javascript - 使用 Classes 定义 JSON 结构
- scala - 如何使用 spark 和 scala 计算迭代计算
- javascript - 使用键 javascript 将嵌套的 json 转换为 CSV
- yocto - 来自外部设备的音频音量
- javascript - 角度形式的条件要求验证
- python - Why does set() in set() not raise a TypeError, unlike {} in set(), [] in set(), set() in {}, [] in {}, or {} in {}?