Struct Cloning with Unexported Fields
In Go, structs with unexported fields present a challenge for cloning objects. Consider a type defined as:
type T struct { S string is []int }
A simple assignment like below will not create an independent copy:
p := T{"some string", []int{10, 20}} q := p
This is because the type's unexported field (is) is inaccessible and cannot be copied over explicitly.
Cloning via Custom Method
One workaround is to provide a Clone method within the package owning the type. However, this only works for types within the same package.
Limitations of Third-Party Types
If a type with unexported fields resides in a third-party package, there is no direct way to clone it. This is by design, as unexported fields should remain private to the declaring package.
Alternative Approach
While it's not possible to clone unexported fields, it is possible to create new structs with empty (zero) values for those fields:
var r somepackage.T s := somepackage.T{S: p.S}
Unsafe Practices
Using the unsafe package is not recommended for this purpose, as it can lead to unexpected and potentially unsafe behavior.
Copying Unexported Fields
When assigning one struct to another of the same type, unexported fields are properly copied. However, modifying those fields is not possible (they can only be nil or the same pointer value as the original).
type person struct { Name string age *int } age := 22 p := &person{"Bob", &age} p2 := new(person) *p2 = *p // Copy unexported field fmt.Println(p2) // Outputs: &{Bob 0x414020}
The above is the detailed content of How Can I Clone Go Structs with Unexported Fields?. For more information, please follow other related articles on the PHP Chinese website!