Skip to content

Instantly share code, notes, and snippets.

@yogesh-desai
Forked from cevaris/struct_as_map_key.go
Created November 16, 2016 19:19
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 yogesh-desai/941b0d114504b9bc0c5cf9ea4f480c6d to your computer and use it in GitHub Desktop.
Save yogesh-desai/941b0d114504b9bc0c5cf9ea4f480c6d to your computer and use it in GitHub Desktop.
Golang: Using structs as key for Maps
package main
import "fmt"
type A struct {
a, b int
}
func MapStructValAsKey(){
// Notice: We are using value of `A`, not `*A`
m1 := make(map[A]string)
a1 := &A{0, 1}
m1[*a1] = "01"
a2 := &A{0, 1}
// Succeeds because map is hashing with
// the `struct` value
_, lookSucceed := m1[*a2]
fmt.Println(m1, lookSucceed)
}
func MapStructPointerAsKey(){
// Notice: We are using pointer of `*A`, not `A`
m1 := make(map[*A]string)
a1 := &A{0, 1}
m1[a1] = "01"
a2 := &A{0, 1}
// Fails because map is hashing with
// the `struct` memory address
_, lookSucceed := m1[a2]
fmt.Println(m1, lookSucceed)
}
func main() {
MapStructValAsKey()
MapStructPointerAsKey()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment