0

I have Tag struct and TableAbstruct interface like below example.

[Tag struct]

type Tag struct {
    Id   int    `db:"id"`
    Name string `db:"Name"`
}
func (tag Tag) Serialize() []string {
    ...
}

[TableAbstruct interface]

type TableAbstruct interface {
    Serialize() []string
}

Xxx() function returns []TableAbstruct, but actual type is []Tag. And below program will work well because Tag includes TableAbstruct interface.

func Xxx() []TableAbstruct {
    result := []TableAbstruct{}
    for i := 0; i < 10; i++ {
        table_obj := Tag{}
        result = append(result, table_obj)
    }
    return result
}

But I want to write like below and I couldn't. I think the problem is TypeError. But I couldn't understand why the error has occurred.

func Xxx() []TableAbstruct {
    result := []Tag{}
    return result
}
mk-tool
  • 325
  • 1
  • 4
  • 10

1 Answers1

1

Go does not have any fanciness around slices and types. Put simply, if you say you are going to return []TableAbstruct, you have to return that exactly. So if you want to return a []Tag, you have to create a slice of []TableAbstruct and then go populate it manually:

func Xxx() []TableAbstruct {
  var returnValue []TableAbstruct
  for _, t := range result {
    returnValue = append(returnValue, t)
  }
  return returnValue
}
poy
  • 10,063
  • 9
  • 49
  • 74