英文:
Which interface does this type implement?
问题
本质上,这里有四个关于Golang接口的问题,每个问题都比前一个稍微难一些。
- 假设我们导入了很多接口,A、B、C、...、G:
import (
"A",
"B",
"C",
// 更多...
"G"
)
然后我们定义了一个类型S:
type S struct {
// 更多...
}
现在如果S "实现" 了其中一个接口:
func (s S) Foo() {
// 更多...
}
截至目前,除了查看和搜索A-G接口的声明之外,还有其他方法可以确定S实现了哪个接口吗?如果没有,是否有一种明确告诉S要实现哪个接口的方法?到目前为止,似乎是根据S实现的接口进行推断。
-
对于同一个示例,如果B、C、D接口都具有相同签名的Foo()方法,那么S实现了哪个接口?这是否取决于从B、C和D导入这些接口的顺序?
-
如果不是导入接口,而是在同一个文件中声明和定义接口B、C、D,但这些接口再次都具有相同签名的Foo()方法,那么S实现了哪个接口?这是否取决于声明或定义这些接口的顺序?
-
如果我们在同一个文件中声明和定义了B、C、D接口,其中B有Foo()方法,C有Bar()方法,D同时具有Foo()和Bar()方法。现在如果S实现了Foo()和Bar(),那么S是实现了B和C,还是只实现了D?
英文:
In essence, four questions are here for Golang interfaces, with each one slightly harder than the one before it.
<ol>
<li>say we imported a lot of interfaces, A, B, C, ..., G <\li>
</ol>
import (
"A",
"B",
"C",
// more ...
"G"
)
and we define a type S:
type S struct {
// more ...
}
now if S "implements" one of the interfaces:
func (s S) Foo() {
// more ...
}
Up to date, is there any other way to tell which interface of A - G does S implement, except for looking and searching into interface declarations of A - G? If no, is there a way to explicitly tell S to implement which interface? So far, it appears that the which interface S implemented is inferred.
-
If, for the same example, B, C, D interfaces all have the Foo() method with the same signature. In this case, which interface does S implement? Does it depend on the order those interfaces are imported from B, C, and D?
-
If, rather than importing interfaces, we declare and define interfaces B, C, D in the same file, but those interfaces again all have Foo() method with the same signature, which interface does S implement? Does it depend on the order those interfaces are declared, or defined?
-
If, we declared and defined B, C, D interfaces in the same file, B has Foo() method, C has Bar() method, and D has both Foo() and Bar(). Now if S implement Foo() and Bar(), then does S implement B and C, or S only implements D?
答案1
得分: 2
-
不是的。(但是顺便提一下,你不导入接口,你导入包。)
-
全部都可以。顺序无关紧要。如果你声明了类型为
B
、C
和D
的变量,它们都可以保存一个S
。 -
全部都可以。在同一个文件或不同的文件中做什么都无关紧要。
-
全部都可以。
S
实现了B
,因为S
有Foo()
。S
实现了C
,因为S
有Bar()
。S
实现了D
,因为S
同时有Foo()
和Bar()
。
英文:
-
No. (But as a side note, you don't import interfaces, you import packages.)
-
All of them. Order doesn't matter. If you declared variables of type
B
,C
, andD
, all of them would be able to hold anS
. -
All of them. What you do in the same or different files doesn't matter.
-
All of them.
S
implementsB
becauseS
hasFoo()
.S
implementsC
becauseS
hasBar()
.S
implementsD
becauseS
has bothFoo()
andBar()
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论