<分区>
看了一些golang的代码,不知道是怎么实现的!有人认识吗? 为什么要这样写?
var _ errcode.ErrorCode = (*StoreTombstonedErr)(nil) // assert implements interface
var _ errcode.ErrorCode = (*StoreBlockedErr)(nil) // assert implements interface
<分区>
看了一些golang的代码,不知道是怎么实现的!有人认识吗? 为什么要这样写?
var _ errcode.ErrorCode = (*StoreTombstonedErr)(nil) // assert implements interface
var _ errcode.ErrorCode = (*StoreBlockedErr)(nil) // assert implements interface
最佳答案
这用于检查类型 T 是否实现了接口(interface) I。
var _ errcode.ErrorCode = (*StoreTombstonedErr)(nil) // assert implements interface
var _ errcode.ErrorCode = (*StoreBlockedErr)(nil)
在上面的代码片段中,第一行检查 StoreTombstonedErr
implmenets errcode.ErrorCode
第二行检查 *StoreBlockedErr
是否实现了 errcode.ErrorCode
。
You can ask the compiler to check that the type T implements the interface I by attempting an assignment using the zero value for T or pointer to T, as appropriate:
type T struct{}
var _ I = T{} // Verify that T implements I.
var _ I = (*T)(nil) // Verify that *T implements I.
如果 T(或相应的 *T)没有实现 I,错误将在编译时被捕获。
如果您希望接口(interface)的用户明确声明他们实现了它,您可以将具有描述性名称的方法添加到接口(interface)的方法集中。例如:
type Fooer interface {
Foo()
ImplementsFooer()
}
类型必须实现 ImplementsFooer 方法才能成为 Fooer
type Bar struct{}
func (b Bar) ImplementsFooer() {}
func (b Bar) Foo() {}
关于golang源码为什么要这样写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51964392/