Home > Backend Development > Golang > How Can I Clone Go Structs with Unexported Fields?

How Can I Clone Go Structs with Unexported Fields?

Susan Sarandon
Release: 2024-12-23 14:09:17
Original
776 people have browsed it

How Can I Clone Go Structs with Unexported Fields?

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
}
Copy after login

A simple assignment like below will not create an independent copy:

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

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}
Copy after login

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}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template