检查值是否实现接口的说明 [英] Explanation of checking if value implements interface

查看:26
本文介绍了检查值是否实现接口的说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过Effective Go"和其他类似这样的问答:golang接口合规性编译类型检查,但我无法正确理解如何使用这种技术.

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 technique.

请看例子:

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
}

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

Is there any simple ways (eg without using reflection) check value if it implements an interface?

推荐答案

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

You only have to check if a value implements an interface if you don't know the value's type. If the type is known, that check is automatically done by the compiler.

如果你真的想检查,你可以用你提供的第二种方法来做:

If you really want to check anyways, you can do it with the second method you gave:

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 类型的变量,但是由于变量名称是 _,所以它被忽略.

What you are doing here, is assigning a pointer of MyType type (and nil value) to a variable of type Somether, but since the variable name is _ it is disregarded.

如果MyType实现了Somether,它会编译并且什么都不做

If MyType implemented Somether, it would compile and do nothing

这篇关于检查值是否实现接口的说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆