golang源代码为什么用这种方式编写

时间:2018-08-22 10:01:54

标签: go types interface

我看到了一些golang代码,但我不知道它是如何工作的!有人知道吗? 为什么要用这种方式写?

var _ errcode.ErrorCode = (*StoreTombstonedErr)(nil) // assert implements interface
var _ errcode.ErrorCode = (*StoreBlockedErr)(nil)    // assert implements interface

并且源代码链接为https://github.com/pingcap/pd/blob/0e216a703776c51cb71f324c36b6b94c1d25b62f/server/core/errors.go#L37

1 个答案:

答案 0 :(得分:1)

这用于检查类型T是否实现接口I。

var _ errcode.ErrorCode = (*StoreTombstonedErr)(nil) // assert implements interface
var _ errcode.ErrorCode = (*StoreBlockedErr)(nil) 

在上面的代码段中,第一行检查StoreTombstonedErr的提示errcode.ErrorCode

第二行检查*StoreBlockedErr是否实现了errcode.ErrorCode

  

您可以要求编译器检查类型T是否实现了   通过尝试使用T的零值进行赋值来接口I   适当时指向T的指针:

type T struct{}
var _ I = T{}       // Verify that T implements I.
var _ I = (*T)(nil) // Verify that *T implements I.

如果T(或* T,相应地)未实现I,则错误将在编译时捕获。

如果希望接口的用户显式声明他们实现了该接口,则可以在接口的方法集中添加一个具有描述性名称的方法。例如:

type Fooer interface {
    Foo()
    ImplementsFooer()
}

然后,类型必须将ImplementsFooer方法实现为Fooer

type Bar struct{}
func (b Bar) ImplementsFooer() {}
func (b Bar) Foo() {}
相关问题