How to Copy a Struct in Go (Shallow vs Deep Copy)

Go copies structs by value (shallow), requiring manual recursion or Clone() methods for deep copies of nested pointers.

Go performs a shallow copy by default when you assign a struct, meaning nested pointers still reference the same memory. To create a deep copy, you must manually allocate new memory for nested pointers and recursively copy their contents. For standard library types like *url.URL, use the built-in Clone() method.

// Shallow copy: s2 shares nested pointers with s1
s2 := s1

// Deep copy: manually allocate and copy nested data
s2 := s1
s2.NestedPtr = &NestedStruct{
    Value: s1.NestedPtr.Value,
}

// Deep copy for *url.URL using standard library
url2 := url1.Clone()