Skip to content

Instantly share code, notes, and snippets.

@feyeleanor
Created December 17, 2015 15:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save feyeleanor/74b7cdcd817a9340a914 to your computer and use it in GitHub Desktop.
Save feyeleanor/74b7cdcd817a9340a914 to your computer and use it in GitHub Desktop.
Example showing difference between storing struct and *struct in a string
package main
import "fmt"
type S struct {
I int
}
func main() {
m1 := map[string]S{"0": S{0}, "1": S{1}}
fmt.Println("map[string]struct")
fmt.Println("\tm1 =", m1)
fmt.Println("\tchange field I via reference")
v := m1["0"]
v.I = 2
fmt.Println("\tm1 =", m1)
fmt.Println()
fmt.Println("\treplace struct in map")
m1["0"] = S{2}
fmt.Println("\tm1 =", m1)
fmt.Println()
m2 := map[string]*S{"0": &S{0}, "1": &S{1}}
fmt.Println("map[string]*struct")
fmt.Printf("\tm2 = map[0:{%v} 1:{%v}]\n", m2["0"].I, m2["1"].I)
fmt.Println("\tchange field I via reference")
r := m2["0"]
r.I = 2
fmt.Printf("\tm2 = map[0:{%v} 1:{%v}]\n", m2["0"].I, m2["1"].I)
fmt.Println()
fmt.Println("\treplace struct in map")
m2["0"] = &S{3}
fmt.Printf("\tm2 = map[0:{%v} 1:{%v}]\n", m2["0"].I, m2["1"].I)
fmt.Println()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment