go - 在 go 中复制指针内容会导致不必要的开销?
问题描述
如果我理解正确,*s = *(*State)(&state)
请将 at 的内容复制&state
到 s 地址(转换*rawState
为之后*State
)。s = (*State)(&state)
但是如果是这样的话,做而不是复制*state
并被GC收集不是更有效吗?或者它是否会导致副作用改变 s / 的值或这样做的其他原因?谢谢!
[0] 中的完整功能:
func (s *State) UnmarshalJSON(b []byte) error {
type rawState State
var state rawState
dec := json.NewDecoder(bytes.NewReader(b))
if s.useJSONNumber {
dec.UseNumber()
}
err := dec.Decode(&state)
if err != nil {
return err
}
*s = *(*State)(&state)
return s.Validate()}
解决方案
那作业:
*s = *(*State)(&state)
是否复制指向的值。这是必需的,因为s
它是一个局部变量,s
一旦函数返回,将任何内容分配给自身将无效。
目的是在s
指向的地方赋值,这就是上面的赋值语句所做的。
using 的目标rawState
是创建一个没有UnmarshalJSON()
方法的新类型,因此传递*rawState
到json.Unmarshal()
不会导致堆栈溢出。
推荐阅读
- node.js - 如何检索 SharePoint 网页代码(html)或抓取共享点网页?
- php - 嘲笑php测试中的碳对象
- ecmascript-6 - 为什么 !在graphql中的字符串之后?
- reactjs - React redux 正确状态更新
- parallel-processing - 如何在 Julia 中同时写入数组的多个索引?
- for-loop - Makefile 从 for 循环更新全局变量
- reactjs - Snowpack & React:热重装/刷新不起作用
- c# - 与解决方案文件夹结构VS2019相同的文件夹结构
- ruby-on-rails - Gem 是否应该假设加载了其他 gem?
- ios - Xcode 不上传构建