4 ms·
> people use a zero value to indicate that a value is missing Go supports returning multiple results. Maybe I don't read enough Go code to understand what's ac
by wahern 5y ago
> people use a zero value to indicate that a value is missing
Go supports returning multiple results. Maybe I don't read enough Go code to understand what's actually popular, but AFAIU the idiomatic way to accomplish this in Go is something like:
if v, exists := lookup(key); exists {
do(v)
}
or
if r, err != foo(); err != nil {
do(r)
}
The compiler, unfortunately, can't enforce proper conditionals. OTOH, unlike C compilers Go won't make any dangerous assumptions about dereferencing nil pointers, which is something.
I'm not sure Generics can help here. What you really want is compiler enforcement of comprehensive condition checks. For example, via pattern matching switch statements. That's easiest to do with optional types as the unwrapping operation creates a simple point for static constraint checking, but in principle the same thing could be accomplished with annotations on multi-value return types that describe the association.
- assbuttbuttass 5y agoI'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)) }