两种不同类型如何在使用接口的golang中实现相同的方法? [英] How can two different types implement the same method in golang using interfaces?
问题描述
type第一个struct {
str string
}
类型第二个结构{
str字符串
}
它们实现接口A:
type A接口{
PrintStr()// print First.str or Second .str
}
像第一个和第二个结构的实现似乎是多余的所以:
func(f First)PrintStr(){
fmt.Print(f.str)
)
func(s Second)PrintStr(){
fmt.Print(s.str)
}
有没有办法让所有实现接口A的结构都有一个实现?像这样的东西,但它似乎并没有工作:
func(a A)PrintStr(){
fmt.Print(a.str)
}
谢谢!
不,您可以创建基本类型,然后将其嵌入到你的2结构,因此只需要基类型的实现:
$ p $ type WithString struct {
str string
类型第一个struct {
WithString
}
类型第二个struct {
WithString
}
类型A接口{
PrintStr()//打印First.str或Second.str
}
func(w WithString)PrintStr(){
fmt.Print(w.str)
}
用法:
a:=第一个{
WithString:WithString {
str:foo,
},
}
Say I have two structs:
type First struct {
str string
}
type Second struct {
str string
}
And I want both of them to implement interface A:
type A interface {
PrintStr() //print First.str or Second.str
}
It seems redundant to have an implementation for both First and Second structs like so:
func (f First) PrintStr() {
fmt.Print(f.str)
}
func (s Second) PrintStr() {
fmt.Print(s.str)
}
Is there a way I can have one implementation for all the structs implementing interface A? Something like this, but it doesn't seem to work:
func (a A) PrintStr() {
fmt.Print(a.str)
}
Thank you!
No you can't, but you could create a base type and then embed it into your 2 struct, therefore only needing an implementation for the base type:
type WithString struct {
str string
}
type First struct {
WithString
}
type Second struct {
WithString
}
type A interface {
PrintStr() //print First.str or Second.str
}
func (w WithString) PrintStr() {
fmt.Print(w.str)
}
Usage:
a := First{
WithString: WithString{
str: "foo",
},
}
Complete Example on Playground
这篇关于两种不同类型如何在使用接口的golang中实现相同的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!