golang源码为什么要这样写

标签 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

最佳答案

这用于检查类型 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/

相关文章:

go - channel 数组的范围

go - 将 map[string]interface{} 数据存储在 diskv 值字段(预期的 []byte)中用于缓存 http 请求

java - 如何将多个接口(interface)分组为一个通用的单个接口(interface)?

c++ - 用于 GUI 的 CSS 或 C++

javascript - Typescript 提示界面中不存在私有(private)属性

go - Golang 中的 Reader 是如何自动循环迭代的?

go - 在 golang 中批量处理来自 ms azure eventhub 的事件

types - 如何在没有赋值的情况下注释 Rust 变量的数据类型?

具有隐式属性类型的 Typescript 泛型

c# - Type.GetType 不区分大小写 - WinRT