douying6206 2019-04-19 03:38
浏览 24

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

I have N functions that return slices of different types.

All of the returned types has a method: func (t *T)GetName() string

I have no control to these functions.

Now I try to combine the N functions to 1:

I created an interface which has only 1 method GetName(), but I get error

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{}}
}

Here returnA works fine but returnAs gives compile error:

prog.go:46:12: cannot use []*A literal (type []*A) as type []Alphabet in return argument

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

Update:

Sorry I did not explain my case clearly,

I have N functions that return slices of different types.

I now use N wrapper functions to return values from original functions.

What I currently have:

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

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

What I want:

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

I'm not good at design patterns, I just feel written this way might be easier for the caller(myself)

  • 写回答

2条回答 默认 最新

  • dongze8698 2019-04-19 03:54
    关注
    func returnAs() (as []Alphabet) {
        for _, a := range []*A{&A{},&A{},&A{}} {
            as = append(as, a)
        }
        return 
    }
    

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

    评论

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题