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 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件