首页 > 解决方案 > 在 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()}

[0] https://github.com/hashicorp/terraform-json/blob/d1018bf93fd9c097133b0159ab8b3c0517a846c9/state.go#L73

标签: gopointerscopy

解决方案


那作业:

*s = *(*State)(&state)

是否复制指向的值。这是必需的,因为s它是一个局部变量,s一旦函数返回,将任何内容分配给自身将无效。

目的是在s指向的地方赋值,这就是上面的赋值语句所做的。

using 的目标rawState是创建一个没有UnmarshalJSON()方法的新类型,因此传递*rawStatejson.Unmarshal()不会导致堆栈溢出。

请参阅相关:在 UnmarshalJSON 函数中调用 json.Unmarshal 而不会导致堆栈溢出


推荐阅读