How to use reflect.Type.Implements

107 views
Skip to first unread message

David DENG

unread,
Mar 19, 2015, 12:40:14 AM3/19/15
to golan...@googlegroups.com
The problem is how to generate a reflect.Type of an interface type? if this is not possible, in which case this method could be used?

Thanks!


Jan Mercl

unread,
Mar 19, 2015, 4:57:22 AM3/19/15
to David DENG, golan...@googlegroups.com
On Thu, Mar 19, 2015 at 5:40 AM David DENG <david...@gmail.com> wrote:

> The problem is how to generate a reflect.Type of an interface type? if this
> is not possible, in which case this method could be used?

For example (http://play.golang.org/p/V7XTlxTC8Q):

package main

import (
"bufio"
"fmt"
"io"
"os"
"reflect"
)

var (
iface        interface{}
ioReader     io.Reader
ioRuneReader io.RuneReader
)

func main() {
bufioReader := bufio.NewReader(nil)
osFile := &os.File{}

iface = bufioReader
t := reflect.TypeOf(iface)
fmt.Println(t.Implements(reflect.TypeOf(&ioReader).Elem()))
fmt.Println(t.Implements(reflect.TypeOf(&ioRuneReader).Elem()))

iface = osFile
t = reflect.TypeOf(iface)
fmt.Println(t.Implements(reflect.TypeOf(&ioReader).Elem()))
fmt.Println(t.Implements(reflect.TypeOf(&ioRuneReader).Elem()))
}

Output.

true
true
true
false

-j



Jesse McNelis

unread,
Mar 19, 2015, 5:03:35 AM3/19/15
to David DENG, golang-nuts


On 19 Mar 2015 15:40, "David DENG" <david...@gmail.com> wrote:
>
> The problem is how to generate a reflect.Type of an interface type? if this is not possible, in which case this method could be used?
>

Get the reflect.Type of a pointer to that interface and then called the .Elem() method to get a reflect.Type of the interface.

David DENG

unread,
Mar 19, 2015, 11:22:05 AM3/19/15
to golan...@googlegroups.com, david...@gmail.com, jes...@jessta.id.au
Thanks guys, the pointer-Elem trick works!
Reply all
Reply to author
Forward
0 new messages