golang,结合2种方法有相同的内容 [英] golang, combine 2 method have same content
本文介绍了golang,结合2种方法有相同的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
2个方法的内容是一样的。
func(t * A)TestGo()错误{
...
return t.abc(); //调用struct
的方法
我可以写一个func能够输入2类型。像这样
fun TestGo(t。?。)错误{
...
return t。 ABC();
}
以后维护起来会比较容易。谢谢!
解决方案
您可以使用此方法为结构创建一个接口:
类型ABCer接口{
abc()错误
}
然后你的 TestGo
函数可以接受这个接口:
func TestGo(t ABCer)错误{
return t.abc()
}
现场演示。
I have 2 method of 2 struct A and B. The content of 2 Method is the same.
func (t *A) TestGo() error {
...
return t.abc(); // call method of struct
}
Could I write a func able to input 2 type. Like this
fun TestGo(t .?.) error {
...
return t.abc();
}
It will easier to maintain in later. Thanks!
解决方案
You could create an interface for structs with this method:
type ABCer interface {
abc() error
}
Then your TestGo
function can accept this interface:
func TestGo(t ABCer) error {
return t.abc()
}
这篇关于golang,结合2种方法有相同的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文