In golang, you can fetch a key from a map using the obvious syntax:
someMap := map[string]string{
//... contents
}
value := someMap["key1"]
// If "key1" exists in someMap, then the value will be returned; else empty string.
Problem: You can't tell missing keys apart from legitimate empty string values
So, you can test for presence using the comma ok idiom
value, ok := someMap["key1"]
if ok {
// we know that "key1" was in the map, even if value is empty string
} else {
// we know that "key1" was NOT in the map
}
What this looks like is that there are two different overloads of the map lookup method, one which returns just a single map value
result, and one which returns the (value, bool)
result, and the compiler seems to be selecting the overload based on how many return values you've said you'd like to receive.
This is quite nice, and I was wondering if it was possible to implement this on my own functions?
E.g:
func fetchValue() (string, bool) {
return "", true
}
func testMain() {
// This works fine, as expected
val, ok := fetchValue()
if ok {
fmt.Println(val)
}
// COMPILE ERROR: Assignment count mismatch: 1 = 2.
val2 := fetchValue()
}
// COMPILE ERROR: fetchValue redeclared in this package
func fetchValue() string {
return ""
}
Is this possible? or is it secret special language sauce that only works for the builtin map
type and nothing else?