go - 如何避免重复 N 次类似的功能

标签 go

我有 N 个函数返回不同类型的 slice 。

所有返回的类型都有一个方法:func (t *T)GetName() string

我无法控制这些功能。

现在我尝试将 N 个函数合并为 1 个:

我创建了一个只有 1 个方法 GetName() 的接口(interface),但是我得到了错误

package main

import (
    //"fmt"
)


type A struct{
}
func (a *A) GetName() string {
return "A"
}

type B struct{
}

func (b *B) GetName() string {
return "B"
}

type Alphabet interface{
  GetName() string
}

func main() {
}
func returnA() Alphabet{
a := &A{} 
return a
}

func returnAs()[]Alphabet{
return []*A{&A{},&A{},&A{}}
}

此处 returnA 工作正常但 returnAs 给出编译错误:

prog.go:46:12: 不能在返回参数中使用 []*A 文字(类型 []*A)作为类型 []Alphabet

https://play.golang.org/p/ZWUhIg31GE5

更新:

对不起,我没有解释清楚我的情况,

我有 N 个函数返回不同类型的 slice 。

我现在使用 N 包装函数从原始函数返回值。

我目前拥有的:

func returnAs()[]*A{
    as := giveMeAs() // giveMeAs() returns []*A 
    return as
}

func returnBs()[]*B{
    bs := giveMeBs() // giveMeBs() returns []*B 
    return bs
}

我想要的:

func returnAlphabet(s string)[]Alphabet {
   switch s{
   case "A":
   return giveMeAs()
   case "B":
   return giveMeBs()
   //...
   }
}

我不擅长设计模式,我只是觉得这样写对调用者(我自己)来说可能更容易

最佳答案

您的函数返回接口(interface)的一部分,因此这就是您需要构造的。你想要的是。

func returnAs() []Alphabet {
    return []Alphabet{&A{},&A{},&A{}}
}

关于go - 如何避免重复 N 次类似的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55756283/

相关文章:

iphone - 使用 Go 为 iPhone 应用程序编写库

mysql - Golang MySQL 错误 - packets.go :33: unexpected EOF

azure - 启用单点登录

http - 禁用公用名验证 - Go HTTP 客户端

html - 如果点击了外部 URL,我们可以重新定向到我们的应用程序吗

go - vim 去 : search for function specification rather than the declaration

sql-server - 如何使用 golang 将 Microsoft SQL varbinary(max) 字段提取到图像中?

Go mod 下载良好,但 golint 在假设下载的依赖项上失败

go - 从 image.RGBA 实现 io.Reader

go - 如何使用作为接口(interface)参数传入的 Struct 来操作解码的 XML