-3

I have a type called EmployeeList which is just an array of Employee structs.

If I have to add/combine EmployeeList objects, I thought I could add them as follows

package main

import (
  "fmt"
)

type Employee struct {
  Id      int    `json:"id"`
  Name string    `json:"name"`
}

type EmployeeList []Employee

func main() {
  listA := EmployeeList{
    Employee{Id: 1, Name: "foo"},
    Employee{Id: 2, Name: "bar"},
  }

  listB := EmployeeList{
    Employee{Id: 3, Name: "baz"},
  }

  // Print the combined lists
  fmt.Println(append(listA, listB))
}

However the append is throwing an error:

./prog.go:24:21: cannot use listB (type EmployeeList) as type Employee in append

I get that it has to do with a mismatched / unexpected type, but I'm not sure how to add these two lists together?

Thanks!

user2490003
  • 10,706
  • 17
  • 79
  • 155

1 Answers1

1

You cannot append an EmployeeList to an array of Employee. But because EmployeeList is defined as a list of Employee, you can unpack that array and append its elements to listA. You can unpack the array with ....

append(listA, listB...)

(refer to a similar answer https://stackoverflow.com/a/16248257/5666087)

jkr
  • 17,119
  • 2
  • 42
  • 68