小编典典

检查值是否实现接口的说明

go

我已经读过“ EffectiveGo”和其他类似的问答:golang接口符合性编译类型检查,但是我仍然无法正确理解如何使用此技术。

请参见示例:

type Somether interface {
    Method() bool
}

type MyType string

func (mt MyType) Method2() bool {
    return true
}

func main() {
    val := MyType("hello")

    //here I want to get bool if my value implements Somether
    _, ok := val.(Somether)
    //but val must be interface, hm..what if I want explicit type?

    //yes, here is another method:
    var _ Iface = (*MyType)(nil)
    //but it throws compile error
    //it would be great if someone explain the notation above, looks weird
}

如果实现了接口,是否有任何简单的方法(例如,不使用反射)检查值?


阅读 243

收藏
2020-07-02

共1个答案

小编典典

如果您不知道值的类型,则只需检查值是否实现了接口。如果类型已知,则该检查由编译器自动完成。

如果您仍然想进行检查,则可以使用您提供的第二种方法进行检查:

var _ Somether = (*MyType)(nil)

在编译时会出错:

prog.go:23: cannot use (*MyType)(nil) (type *MyType) as type Somether in assignment:
    *MyType does not implement Somether (missing Method method)
 [process exited with non-zero status]

您在这里所做的就是将MyType类型(和nil值)的指针分配给type 的变量Somether,但是由于变量名_是忽略的。

如果MyType实施Somether,它将编译且不执行任何操作

2020-07-02