Go 如何在接口中使用类型别名
考虑以下计划:Go 如何在接口中使用类型别名,go,Go,考虑以下计划: package main import ( "fmt" ) type MyMethod func(i int, j int, k int) (string, error) type MyInterface interface { Hello(i int, j int, k int) (string, error) } type myMethodImpl struct {} func (*myMethodImpl) Hello(i int, j int, k
package main
import (
"fmt"
)
type MyMethod func(i int, j int, k int) (string, error)
type MyInterface interface {
Hello(i int, j int, k int) (string, error)
}
type myMethodImpl struct {}
func (*myMethodImpl) Hello(i int, j int, k int) (string, error) {
return fmt.Sprintf("%d:%d:%d\n", i, j, k), nil
}
func main() {
var im MyInterface = &myMethodImpl{}
im.Hello(0, 1, 2)
}
如何在接口声明中使用MyMethod,而不是重复方法签名?这里混合了两种不同的东西。一个是定义一个类型,它是一个函数。当您希望该类型位于另一个类型中时,需要使用结构 将代码更改为可能的解决方案1(不太惯用): 另一个解决方案是将其更改为使用接口。该解决方案是您的代码,只是没有MyMethod的类型定义 但两者之间的区别是什么 如果将func定义为类型,则在创建函数时需要声明它
var hello MyMethod = func(i int, j int, k int) (string, error) {
return fmt.Sprintf("%d:%d:%d\n", i, j, k), nil
}
现在hello
的类型正好是MyMethod
。如果有其他类型,例如:
type YourMethod func(i int, j int, k int) (string, error)
hello
仍然只是类型MyMethod
要定义接口,您需要一个。但是类型
MyMethod
不是一种方法。这只是一个例子。因此,函数类型与方法定义不同。对于go,如果您想将字符串定义为方法,则相同。谢谢您的回答。但我不认为它完全回答了我的问题。也许我问的问题不对。难道没有办法共享方法签名吗?我的问题的全部要点是我有一个具有大量参数的方法。当我想定义接口和类型时,我可以避免重复吗?我将在多个接口和结构中使用它。。如果我没有看错的话,从你的回复来看似乎没有办法实现它。我认为在Go中定义一个类型作为一个方法是不可能的。为什么要这样做?这样的混合会使代码无法阅读。谢谢你的回答。如果需要,我将按照您的建议使用结构嵌入。
type YourMethod func(i int, j int, k int) (string, error)