Go - 如何明确声明结构正在实现接口?

The*_*chu 5 standards inheritance interface go

由于Go非常重视接口,我想知道如何在一些方法缺失的情况下明确说明一个结构是为了清晰和错误检查而实现一个接口?到目前为止,我已经看到了两种方法,我想知道哪种方法是正确的并且符合Go规范.

方法1 - 匿名字段

type Foo interface{
    Foo()
}

type Bar struct {
    Foo
}
func (b *Bar)Foo() {
}
Run Code Online (Sandbox Code Playgroud)

方法2 - 显式转换

type Foo interface{
    Foo()
}

type Bar struct {
}
func (b *Bar)Foo() {
}
var _ Foo = (*Bar)(nil)
Run Code Online (Sandbox Code Playgroud)

这些方法是否正确,还是有其他方法可以做这样的事情?

One*_*One 8

方法2是正确的方法1,方法1你只是嵌入一个类型并覆盖它的功能.如果你忘了覆盖它,你最终会得到一个nil指针取消引用.


cap*_*aig 5

我很少需要声明这个,因为在我的包中几乎总是有我使用结构体作为接口的地方。我倾向于遵循在可能的情况下保持结构不公开的模式,并且仅通过“构造函数”函数提供它们。

type Foo interface{
  Foo()
}

type bar struct {}
func (b *bar)Foo() {}

func NewBar() Foo{
  return &bar{}
}
Run Code Online (Sandbox Code Playgroud)

如果bar不满足Foo,则不会编译。我没有添加构造来声明该类型实现了接口,而是确保我的代码在某个时候将它用作接口。