dougan5772 2016-07-14 08:37
浏览 52
已采纳

如何克隆未导出字段的结构?

If I have a type defined as:

type T struct {
    S  string
    is []int
}

then how can I go about cloning an object of this type? If I do a simple assignment:

p := T{"some string", []int{10, 20}}
q := p

Then any changes made to the []int affect both objects. Since T.is is not exported, it cannot be copied over explicitly, even if extracted using reflect.

I'm currently supplying a Clone method in the package of the type itself. But that doesn't help with similar types in other packages. Is there another way to do this?

  • 写回答

1条回答 默认 最新

  • doufei3152 2016-07-14 09:23
    关注

    You can't. That's the point of unexported fields: only the declaring package can modify them.

    Note that if the T type is declared in another package, you can't even write:

    p := somepackage.T{"some string", []int{10, 20}}
    

    because this would implicitly try to set the unexported T.is field and thus results in a compile-time error:

    implicit assignment of unexported field 'is' in somepackage.T literal
    

    If you own (or you can modify) the package, best is to provide a Clone() method or function, or provide a SetIs() method for the type T. If a 3rd party package does not provide such functionality, there's nothing you can do about it.

    Note that using package unsafe it is possible to do such things, but as its name says: it's unsafe and you should stay away from it.

    Also note that you can create new values of T where is is not copied but will be the zero value of its type (which in case of []int will be nil):

    var r somepackage.T
    s := somepackage.T{S: p.S}
    
    fmt.Printf("%q
    ", r)
    fmt.Printf("%q
    ", s)
    

    Which will output:

    {"" []}
    {"some string" []}
    

    But you can't set any non-zero value for the unexported field T.is.

    Do note that you can make "exact" copies of structs having unexported fields by simply assigning them to another struct variable (of the same type), which will properly copy the unexported fields too.

    Like in this example:

    type person struct {
        Name string
        age  *int
    }
    
    age := 22
    p := &person{"Bob", &age}
    fmt.Println(p)
    
    p2 := new(person)
    *p2 = *p
    fmt.Println(p2)
    

    Which will output (try it on the Go Playground):

    &{Bob 0x414020}
    &{Bob 0x414020}
    

    Which we can even generalize using reflect without relying on the concrete type:

    type person struct {
        Name string
        age  *int
    }
    
    age := 22
    p := &person{"Bob", &age}
    fmt.Println(p)
    
    v := reflect.ValueOf(p).Elem()
    vp2 := reflect.New(v.Type())
    vp2.Elem().Set(v)
    fmt.Println(vp2)
    

    Try this one on the Go Playground.

    But what we can't do is change the person.age unexported field to point to something else. Without help of the declaring package, it can only be nil or the same pointer value (pointing to the object as the original field).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在不同的执行界面调用同一个页面
  • ¥20 基于51单片机的数字频率计
  • ¥50 M3T长焦相机如何标定以及正射影像拼接问题
  • ¥15 keepalived的虚拟VIP地址 ping -s 发包测试,只能通过1472字节以下的数据包(相关搜索:静态路由)
  • ¥20 关于#stm32#的问题:STM32串口发送问题,偶校验(even),发送5A 41 FB 20.烧录程序后发现串口助手读到的是5A 41 7B A0
  • ¥15 C++map释放不掉
  • ¥15 Mabatis查询数据
  • ¥15 想知道lingo目标函数中求和公式上标是变量情况如何求解
  • ¥15 关于E22-400T22S的LORA模块的通信问题
  • ¥15 求用二阶有源低通滤波将3khz方波转为正弦波的电路