Skip to content

Instantly share code, notes, and snippets.

@cevaris
Last active October 20, 2023 03:18
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save cevaris/24cc9da7b14731204c79 to your computer and use it in GitHub Desktop.
Save cevaris/24cc9da7b14731204c79 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()
}
@cevaris
Copy link
Author

cevaris commented Mar 2, 2015

Output

map[{0 1}:01] true
map[0x104361c8:01] false

Go Play: Run it yourself here
http://play.golang.org/p/JC0a4GsaYO

@lwmonster
Copy link

You are using a pointer instead of a struct as the key

@bmcivor
Copy link

bmcivor commented Sep 18, 2018

yeah.. name of this is misleading

@mhewedy
Copy link

mhewedy commented Sep 27, 2019

You saved my day .... Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment