Skip to content

Instantly share code, notes, and snippets.

@chakrit
Last active March 23, 2018 14:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chakrit/8157474 to your computer and use it in GitHub Desktop.
Save chakrit/8157474 to your computer and use it in GitHub Desktop.
Testing golang's map behavior when the map is nil. Map is defined in the spec as being a reference type (i.e. you can assign maps to multiple variables but they would share the underlying storage). In this case, you can actually index a nil map, but not add values to it. This is nice but could a bit surprising when you are testing for your code'…
package main
import "fmt"
type Values map[string]string
func main() {
var v Values = nil
fmt.Printf("%-15s\t%-15s\t%-15s\n", "nil", "result", "ok")
result, ok := v["test"]
fmt.Printf("%-15v\t%-15v\t%-15v\n", v == nil, result, ok)
// v["test"] = "asdf" // <-- this would panic
v = Values(make(map[string]string, 8))
result, ok = v["test"]
fmt.Printf("%-15v\t%-15v\t%-15v\n", v == nil, result, ok)
v["test"] = "(string)"
result, ok = v["test"]
fmt.Printf("%-15v\t%-15v\t%-15v\n", v == nil, result, ok)
}
nil result ok
true false
false false
false (string) true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment