Re:Go Developer Survey 2022 Q2 Results
by majewsky on Thursday September 08, 2022 @06:43PM
(#32773022)
> myFunc()! panics if there is an err
You can do this with generics today:
func must[T](val T, err error) T {
if err != nil {
panic(err.Error())
}
return val
}
//usage example
file := must(os.Create("out.txt"))
defer file.Close()
bytesWritten := must(file.Write([]byte("Hello World\n")))
We have something like this in our internal utility library. I'm getting some serious mileage out of this when using Go as a script language, where error propagation is not as important as for a regular application or a library.
> myFunc()^ returns the err if there is one
You can also do this with generics:
func geterr[T](val T, err error) {
return err
}
It is true that must() and geterr() are slightly more verbose than single-character operators, but I'd argue having a word instead of a symbol is much more readable. Besides, ^ cannot be used as a postfix unary operator because it's already a binary operator. That would create a grammar ambiguity.
You can do this with generics today:
We have something like this in our internal utility library. I'm getting some serious mileage out of this when using Go as a script language, where error propagation is not as important as for a regular application or a library.> myFunc()^ returns the err if there is one
You can also do this with generics:
It is true that must() and geterr() are slightly more verbose than single-character operators, but I'd argue having a word instead of a symbol is much more readable. Besides, ^ cannot be used as a postfix unary operator because it's already a binary operator. That would create a grammar ambiguity.