【问题标题】:golang source code why write in this way [duplicate]golang源码为什么要这样写[重复]
【发布时间】:2019-01-28 13:40:07
【问题描述】:

我看到了一些 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

【问题讨论】:

    标签: go types interface


    【解决方案1】:

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

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

    在上面的代码中 sn -p 第一行检查 StoreTombstonedErr implmenets errcode.ErrorCode

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

    您可以要求编译器检查类型 T 是否实现了 通过尝试使用 T 的零值或 指向 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() {}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多