Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing generic error handling function without generics

I know that Go will not have generics in the future and there are some recommendations to replace them by other constructs. But with my example below I got stuck.

func P(any interface{}, err error) (interface{}) {
    if err != nil {
        panic("error: "+ err.Error())
    }
    return any
}

As you might guess, I'm trying to just fail on any error and want to put P() just around any function that is returning two results and the second is an error. This is working fine, but any is losing it's type information and is only an empty interface in the result.

As I'm also calling lib functions I don't see a way to address this with Interfaces or Reflection.

Any ideas? Am I totally on the wrong track or close to the goal?

like image 882
mheinzerling Avatar asked Mar 18 '15 08:03

mheinzerling


2 Answers

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{}.

like image 97
VonC Avatar answered Oct 12 '22 12:10

VonC


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)

like image 35
icza Avatar answered Oct 12 '22 13:10

icza