How to get the reflect.Type of an interface?

前端 未结 3 2059
后悔当初
后悔当初 2020-12-15 17:37

In order to determine whether a given type implements an interface using the reflect package, you need to pass a reflect.Type to reflect.Type.Implements(). How do you get o

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-15 18:22

    Even Shaws response is correct, but brief. Some more details from the reflect.TypeOf method documentation:

    // As interface types are only used for static typing, a common idiom to find
    // the reflection Type for an interface type Foo is to use a *Foo value.
    
    writerType := reflect.TypeOf((*io.Writer)(nil)).Elem()
    
    fileType := reflect.TypeOf((*os.File)(nil)).Elem()
    fmt.Println(fileType.Implements(writerType))
    

提交回复
热议问题