How to clone a structure with unexported field?

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\n", r)
fmt.Printf("%q\n", 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).

Leave a Comment