如何将 golang 结构标记为实现接口?

huangapple go评论151阅读模式
英文:

How to mark golang struct as implementing interface?

问题

我有一个接口:

type MyInterface interface {
...
}

我想标记我的结构体实现了这个接口。我认为在Go语言中这是不可能的,但我想要确定一下。

我尝试了以下代码,但我认为它会生成一个实现接口的匿名变量。我是对的吗?

type MyStruct struct {
...
MyInterface
}
英文:

I have interface:

  type MyInterface interface {
  ...
  }

and I want to mark that my struct implements it. I think it is not possible in go, but I want to be certain.

I did the following, but I think it results in an anonymous variable that implements interface. Am I right?

  type MyStruct struct {
    ...
    MyInterface
  }

答案1

得分: 66

在Go语言中,实现接口是隐式的。不需要显式地标记它作为接口的实现。虽然有点不同,但你可以使用赋值来测试一个类型是否实现了接口,如果没有实现,它将在编译时产生错误。示例如下(来自Go的常见问题页面):

type T struct{}
var _ I = T{}       // 验证T是否实现了I接口。
var _ I = (*T)(nil) // 验证*T是否实现了I接口。

回答你的第二个问题,是的,这意味着你的结构体由实现了该接口的类型组成。

英文:

In Go, implementing an interface is implicit. There is no need to explicitly mark it as implementing the interface. Though it's a bit different, you can use assignment to test if a type implements an interface and it will produce a compile time error if it does not. It looks like this (example from Go's FAQ page);

type T struct{}
var _ I = T{}       // Verify that T implements I.
var _ I = (*T)(nil) // Verify that *T implements I.

To answer your second question, yes that is saying your struct is composed of a type which implements that interface.

huangapple
  • 本文由 发表于 2015年10月13日 04:19:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/33089523.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定