Checking for built-in error type

Skip to first unread message

Erik Unger

Jul 17, 2012, 1:27:42 PM7/17/12
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.


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


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

typeof(MyStruct) or

looks a lot better to me than:


Rob Pike

Jul 17, 2012, 1:35:45 PM7/17/12
to Erik Unger,
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

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:


Vanja Pejovic

Jul 17, 2012, 1:38:03 PM7/17/12
to Erik Unger,
You might be trying to do something like this:

Rob 'Commander' Pike

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


Rob Pike

Jul 17, 2012, 1:44:17 PM7/17/12
to Vanja Pejovic, Erik Unger,
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.

Reply all
Reply to author
0 new messages