how to get the reflect.Type of an interface

4,070 views
Skip to first unread message

Petar Maymounkov

unread,
May 25, 2012, 11:52:27 AM5/25/12
to golan...@googlegroups.com
I hope I am not missing something obvious here:

I am reflect/inspecting the types of the arguments passed to some function.

I need to verify that the first argument is of type some known interface X.

I am holding the reflect.Type of the argument. And I need to create a reflect.Type for the interface X,
so that I can compare them.

The problem = I cannot see how to get the reflect.Type of an interface.

Thanks

Petar Maymounkov

unread,
May 25, 2012, 11:54:51 AM5/25/12
to golan...@googlegroups.com
Got it. I saw this in rpc/server.go:

// Precompute the reflect type for error.  Can't use error directly
// because Typeof takes an empty interface value.  This is annoying.
var typeOfError = reflect.TypeOf((*error)(nil)).Elem()

This is how you do it. Not straightforward, but it's ok :)

P

Carlos Castillo

unread,
May 29, 2012, 4:44:42 PM5/29/12
to golan...@googlegroups.com
Um.. under the column of "missing something obvious", since the interface type you are comparing it to is KNOWN, is there a reason why you can't:

type T interface {
DoSomething()
}

// Let the compiler handle it
func fn (arg T) {
}

Or if you are making a function that takes different sets of parameters:

type U interface {
DoSomethingElse()
}

// Use a type switch
func fn2 (arg interface{}) {
  switch v := arg.(type) {
    case T: v.DoSomething()
    case U: v.DoSomethingElse()
  }
}

// Use type assertions
func fn3 (arg interface{}) {
  if t, ok := arg.(T) ; ok {
    t.DoSomething()
  }
  if u, ok := arg.(U) ; ok {
   u.DoSomethingElse()
  }
}

Unless of course, you are using values to which you don't know the types you want to check. (You did say "known interface X")

David Symonds

unread,
Mar 20, 2013, 7:38:05 PM3/20/13
to far...@gmail.com, golang-nuts
On Thu, Mar 21, 2013 at 2:07 AM, <far...@gmail.com> wrote:

> var typeOfError = reflect.TypeOf(error(nil))
> should work also

That doesn't work. You can't store an interface value in another
interface value, so the reflect package will only see a nil
interface{}.

Hraban Luyat

unread,
Apr 17, 2013, 12:13:04 AM4/17/13
to golan...@googlegroups.com
sometimes you don't have the value only a reflect.Type
Reply all
Reply to author
Forward
0 new messages