英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论