4 ms·
I'm talking about optional inputs, you're right that multi-return works for optional outputs. How would you write a function that takes a string, but can use s
by assbuttbuttass 5y ago
I'm talking about optional inputs, you're right that multi-return works for optional outputs.
How would you write a function that takes a string, but can use some default if none is provided?
Common way:
func f(s string) {
if s == "" {
s = "default"
}
...
}
- vishvananda 5y agoYou could always use a pointer for this, but admittedly it is pretty ugly when compared to a true optional type: func f(s *string) string { ret := "" if s == nil { ret = "default" } else { ret = *s } return ret } func main() { s := "foo" fmt.Println("Hello, " + f(&s)) fmt.Println("Hello, " + f(nil)) }