Checking for built-in error type

2,010 views
Skip to first unread message

Erik Unger

unread,
Jul 17, 2012, 1:27:42 PM7/17/12
to golan...@googlegroups.com
Is there a clean way to check if a type is the built-in error type?

The best thing I have figured out is:

func IsErrorType(t reflect.Type) bool {
return t == reflect.TypeOf(func(error) {}).In(0)
}

I have suggested before, that having a typeof operator or function that returns a reflect.Type would make some things cleaner and mor readable.

Like:

func IsErrorType(t reflect.Type) bool {
return t == typeof(error)
}

Or:

func IsErrorType(t reflect.Type) bool {
return t == error.(type)
}

Also
typeof(MyStruct) or
MyStruct.(type)

looks a lot better to me than:
reflect.TypeOf((*MyStruct)(nil)).Elem()


-Erik

Rob Pike

unread,
Jul 17, 2012, 1:35:45 PM7/17/12
to Erik Unger, golan...@googlegroups.com
Your question might reprsent a misunderstanding. The "built-in error
type" is not a concrete type but an interface type. Are you asking if
the value is statically of that type, or dynamically? The difference
is important. See the "laws of reflection" blog post if this question
confuses you.

I believe you want to ask, "does this type implement the error
interface", which is the dynamic question. For that, use
reflect.Implements.

If for some reason, very unlikely, you want the static question, just
develop a reflect.Type representing 'error' and use simple equality,
like this

errorType = reflect.TypeOf((*error)(nil)).Elem()

if t == errorType { ... }

I suspect, though, that if you need to use this mechanism but haven't
figured it out yourself, you've talked yourself into a strange corner
and should read the blog post to find your way back:
http://blog.golang.org/2011/09/laws-of-reflection.html

-rob

Vanja Pejovic

unread,
Jul 17, 2012, 1:38:03 PM7/17/12
to Erik Unger, golan...@googlegroups.com
You might be trying to do something like this:

Rob 'Commander' Pike

unread,
Jul 17, 2012, 1:40:09 PM7/17/12
to Vanja Pejovic, Erik Unger, golan...@googlegroups.com
Perhaps, but again that is the dynamic question, not the static one.

-rob

Rob Pike

unread,
Jul 17, 2012, 1:44:17 PM7/17/12
to Vanja Pejovic, Erik Unger, golan...@googlegroups.com
A related point: Early users of Go lean too much on reflection. Few Go
programs outside of low-level libraries should need to use reflection.
If you find yourself wanting reflection on day 1, ask us about what
you're up to. Chances are there's another approach that will be
simpler and faster.

A key detail of Vanja's suggestion, for those following along at home,
is that it avoids reflection and is therefore Good. Whether it solves
the original question remains unresolved.

-rob
Reply all
Reply to author
Forward
0 new messages