Explanation of checking if value implements interface

前端 未结 4 1289
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-05 04:22

I\'ve read \"Effective Go\" and other Q&As like this: golang interface compliance compile type check , but nonetheless I can\'t understand properly how to use this techn

4条回答
  •  有刺的猬
    2020-12-05 04:59

    It is also possible to use Implements(u Type) bool method of reflect.Type in the following way:

    package main
    
    import (
        "reflect"
    )
    
    type Somether interface {
        Method() bool
    }
    
    type MyType string
    
    func (mt MyType) Method() bool {
        return true
    }
    
    func main() {
    
        inter := reflect.TypeOf((*Somether)(nil)).Elem()
    
        if reflect.TypeOf(MyType("")).Implements(inter) {
            print("implements")
        } else {
            print("doesn't")
        }
    }
    

    You can read more on that in the documentation.

提交回复
热议问题