代码之家  ›  专栏  ›  技术社区  ›  xren

歌朗源代码为什么这样写[复制]

  •  -1
  • xren  · 技术社区  · 6 年前

    我看到了一些金刚代码,我不知道它是怎么工作的!有人知道吗? 为什么要这样写?

    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 回复  |  直到 6 年前
        1
  •  1
  •   Himanshu    6 年前

    这用于检查if type T是否实现接口I。

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

    StoreTombstonedErr 指令集 errcode.ErrorCode

    当第二行检查时 *StoreBlockedErr 工具 errcode.errcode错误代码 .

    通过尝试使用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方法才能成为fooor

    type Bar struct{}
    func (b Bar) ImplementsFooer() {}
    func (b Bar) Foo() {}