Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[Golang Named Return Zero Value] #go #golang #zero #named #return
package main
import (
"fmt"
)
func GetString(key string) (val string) {
// 'named' return value are initialized to their zero value
// meaning we can proxy the zero value through to a nested function
//
return GetStringDefault(key, val)
}
func GetStringDefault(key string, defaultValue string) string {
m := map[string]string{
"foo": "bar",
"abc": "xyz",
}
v, ok := m[key]
if !ok {
return defaultValue
}
return v
}
func main() {
defaultValue := "no key found"
// if you care about getting a default value back
// then use the GetStringDefault function
//
fmt.Println(GetStringDefault("foo", defaultValue)) // bar
fmt.Println(GetStringDefault("abc", defaultValue)) // xyz
fmt.Println(GetStringDefault("xxx", defaultValue)) // no key found
// if you don't care about getting a default value back
// then use the GetString function, and you'll now get back a zero value
//
fmt.Println(GetString("foo")) // "bar"
fmt.Println(GetString("abc")) // "xyz"
fmt.Println(GetString("xxx")) // "" << zero value for type string
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.