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)