-1

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)

sfdcnoob
  • 777
  • 2
  • 8
  • 19
  • 1
    Go does not allow *directly* converting a slice of one type to a slice of another, besides reflection there's nothing you can do but to loop over one to construct the other. https://stackoverflow.com/a/12754757/965900 – mkopriva Apr 19 '19 at 04:44
  • If this is the use case, then `giveMeAs`, `giveMeBs`, etc should probably return `[]Alphabet`. – Adrian Apr 19 '19 at 13:59

2 Answers2

4

Your function returns a slice of interfaces, so that's what you need to construct. What you want is.

func returnAs() []Alphabet {
    return []Alphabet{&A{},&A{},&A{}}
}
superfell
  • 18,780
  • 4
  • 59
  • 81
1
func returnAs() (as []Alphabet) {
    for _, a := range []*A{&A{},&A{},&A{}} {
        as = append(as, a)
    }
    return 
}

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

beiping96
  • 644
  • 3
  • 12