了解冲突接口
Understanding conflicting Interfaces
我正在尝试理解界面概念。
以下是我的测试代码:
package main
import "fmt"
//interface
type InterfaceA interface {
A() string
}
//interface
type InterfaceB interface {
A() string
}
//user defined type structure
type structure struct {
a string
}
//implementing A(), but which A() ?
func (strt structure) A() string {
return strt.a
}
func main() {
fmt.Println("Start")
variable := structure{"hello"}
fmt.Println(variable.A())
}
根据文档,我了解到没有像其他语言那样明确提及“实施”。但是当我调用 variable.A()
时,我的类型 structure
使用的是哪个接口? InterfaceA
还是 InterfaceB
?另外,我真的正确地实现了接口吗?
你们的接口没有相互冲突;接口不冲突。它们可以相互冗余,因为它们描述的是同一件事,但这不会造成冲突或任何其他有形问题。
至于structure
使用的是哪个界面:都没有。结构等具体类型不使用接口,而是实现它们。接口的实现是隐式和自动的。它只是一个事实陈述,而不是一种机制(除非你明确地使用它)。此外,这两个接口都不会在您的程序中使用到任何程度。您的 variable
是一个 structure
,正被用作 structure
。它 可以 用作 或者 InterfaceA
或 InterfaceB
,或者它们在不同的时间使用,但是你正在做在这个例子中没有这样的东西。
请参阅 Burak 的回答,了解您如何可以 通过接口使用 structure
值。
当您调用 variable.A()
时,您没有使用任何接口。您正在调用 structure
.
类型的方法
您可以使用接口调用相同的方法:
variable := structure{"hello"}
var ia InterfaceA
ia=variable
ia.A() // This calls variable.A
var ib InterfaceB
ib=variable
ib.A() // This also calls variable.A
我正在尝试理解界面概念。 以下是我的测试代码:
package main
import "fmt"
//interface
type InterfaceA interface {
A() string
}
//interface
type InterfaceB interface {
A() string
}
//user defined type structure
type structure struct {
a string
}
//implementing A(), but which A() ?
func (strt structure) A() string {
return strt.a
}
func main() {
fmt.Println("Start")
variable := structure{"hello"}
fmt.Println(variable.A())
}
根据文档,我了解到没有像其他语言那样明确提及“实施”。但是当我调用 variable.A()
时,我的类型 structure
使用的是哪个接口? InterfaceA
还是 InterfaceB
?另外,我真的正确地实现了接口吗?
你们的接口没有相互冲突;接口不冲突。它们可以相互冗余,因为它们描述的是同一件事,但这不会造成冲突或任何其他有形问题。
至于structure
使用的是哪个界面:都没有。结构等具体类型不使用接口,而是实现它们。接口的实现是隐式和自动的。它只是一个事实陈述,而不是一种机制(除非你明确地使用它)。此外,这两个接口都不会在您的程序中使用到任何程度。您的 variable
是一个 structure
,正被用作 structure
。它 可以 用作 或者 InterfaceA
或 InterfaceB
,或者它们在不同的时间使用,但是你正在做在这个例子中没有这样的东西。
请参阅 Burak 的回答,了解您如何可以 通过接口使用 structure
值。
当您调用 variable.A()
时,您没有使用任何接口。您正在调用 structure
.
您可以使用接口调用相同的方法:
variable := structure{"hello"}
var ia InterfaceA
ia=variable
ia.A() // This calls variable.A
var ib InterfaceB
ib=variable
ib.A() // This also calls variable.A