-2

i have 2 structs with a slice inside like this:

type BookX struct {
  SomeValue string
  Book1 []Book1
}
type Book1 struct {
  Name string
  Author string
}

type BookY struct {
  SomeValue string
  Book2 []Book2
}
type Book2 struct {
  Name string
  Author string
}

And i want to pass the values inside the first slice in the struct BookX to the other slice inside the BookY.

Tried this way but doesn't work:

func someName(bookX BookX){
  var bookY BookY
  bookY.Book2 = append(bookY.Book2, bookX.Book1...)
}

Mtac
  • 61
  • 5

1 Answers1

2

Book1 and Book2 are the diffrent type even they have same members. You can not append []Book1 to []Book2.

One solution is to create a Book2 instance from Book1 and add them to []Book2.

func someName(bookX BookX){
  var bookY BookY
  for _, book1 := range bookx.Book1 {
    book2 := Book2 {
      Name: book1.Name,
      Author: book1.Author,
    }
    bookY.Book2 = append(bookY.Book2, book2)
  }
}

N.F.
  • 3,844
  • 3
  • 22
  • 53