2015-01-06 57 views
8

我读过“Effective Go”和其他Q &就像这样:golang interface compliance compile type check,但是我无法正确理解如何使用这种技术。检查值是否实现接口的说明。 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 
} 

有没有简单的方法(例如,不使用反射)校验值,如果它实现了一个接口?

+1

怎么样_,确定:=接口{}(VAL)(Somether)。? – c0ming

回答

14

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

如果你真的想反正检查,你可以用你给的第二种方法做到这一点:这将错误在编译时

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值)的指针分配给类型为Somether的变量,但由于变量名称是_,因此忽略它。

如果MyType实施Somether,它会编译和什么也不做

+0

感谢您的解释! –

+0

为什么黑色标识符不一定需要是'* Somether',因为右手有一个指向MyType的指针?我还在学习。 :-) –

+0

你可以想象一个像容器这样的接口值,只要它实现了正确的方法,你就可以放入任何你想要的东西。它可以直接包含一个指向结构体或结构体的指针。作为一个经验法则,你永远不需要制作一个指向接口值的指针 –