Last active
March 23, 2018 14:57
-
-
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'…
This file contains 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 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) | |
} |
This file contains 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
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