Writing generics function without generics
One solution would be to go generate
your P()
function, one for each concrete type you need to work with.
See examples in:
- "Generic programming in Go using "
go generate
"". - "joeshaw/gengen"
- "cheekybits/genny"
- "clipperhouse/gen"
- "Achieving type generic functions in Go, without using reflections"
That would make calling those lib functions easier, since the concrete P () implementations generated would use the right type instead of interface{}.
What you want to do would require generics but as you already mentioned, Go does not support generic types. Therefore, you can't create a general function which would not lose the type.
You have to create such a function for each type you want to support. Note that the standard library already contains some of these going under the name MustXXX()
, which you can use out of the box, for example:
template.Must(t *Template, err error) *Template
Or "similar" functions which suppress the error
but if one still occurs, panics, for example:
regexp.MustCompile(str string) *Regexp
(suppresses error
but panics if str
is not a valid regexp)
If you plan on just panicking on errors (bad idea) or logging them, then just define a function to do so and use it. E.g.
func checkErr(err error) {
if err != nil {
log.Println(err)
}
}
// ...
func foo() {
a, err := doA()
checkErr(err)
b, err := doB()
checkErr(err)
// etc.
}
The user twotwotwo has already linked to the Errors are values article that shows more examples on how to make error handling less repetitive. But I would recommend just write the whole if err != nil
thing, because in my experience every third error, if not second, requires some additional handling.