Created
December 17, 2015 15:12
-
-
Save feyeleanor/74b7cdcd817a9340a914 to your computer and use it in GitHub Desktop.
Example showing difference between storing struct and *struct in a string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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