Skip to content

Instantly share code, notes, and snippets.

@alexhudici
Created April 14, 2019 00:45
Show Gist options
  • Save alexhudici/11fd407f9fc2bc80069cca262216d2ea to your computer and use it in GitHub Desktop.
Save alexhudici/11fd407f9fc2bc80069cca262216d2ea to your computer and use it in GitHub Desktop.
differences in copying pointers to a struct and modifying contents within it
// https://play.golang.org/p/juDjWm9VC44
package main
import "fmt"
type T struct {
Id int
Name string
Flurb []string
}
func Copy(a *T, b *T) error {
b.Id = 5
b.Name = "gert"
a = b
return nil
}
func CopyThatActuallyCopies(a *T, b *T) error {
b.Id = 5
b.Name = "gert"
*a = *b
return nil
}
func main() {
var a = &T{1, "one", []string{"dl"}}
var b = &T{2, "two", []string{"bb"}}
fmt.Println(a, b)
Copy(a, b)
fmt.Println(a, b)
CopyThatActuallyCopies(a, b)
fmt.Println(a, b)
//pointers within the struct will get copied as pointers so they are all pointing to the same instance
b.Flurb[0] = "asdf"
fmt.Println(a, b)
//modifying the slice itself makes it a new object so it is no longer pointing to the same instance as the one that was copied
b.Flurb = append(b.Flurb, "blabla")
fmt.Println(a, b)
b.Flurb[0] = "0000"
fmt.Println(a, b)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment