Writing generic error handling function without generics

Issue

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?

Solution

One solution would be to go generate your P() function, one for each concrete type you need to work with.
See examples in:

That would make calling those lib functions easier, since the concrete P () implementations generated would use the right type instead of interface{}.

Answered By – VonC

Answer Checked By – Gilberto Lyons (GoLangFix Admin)

Leave a Reply

Your email address will not be published.