在两个包含切片的结构体之间传递值。

huangapple go评论80阅读模式
英文:

Passing values between two structs thats have a slice inside

问题

我有两个结构体,里面都有一个切片,像这样:

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
}

我想将第一个结构体BookX中的切片的值传递给第二个结构体BookY中的切片。

尝试了以下方式,但不起作用:

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

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...)
}

答案1

得分: 2

Book1Book2是不同类型的,即使它们具有相同的成员。你不能将[]Book1追加到[]Book2中。

一种解决方案是从Book1创建一个Book2实例,并将它们添加到[]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)
  }
}

请注意,这只是一个示例代码,具体实现可能需要根据你的需求进行调整。

英文:

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)
  }
}

huangapple
  • 本文由 发表于 2022年5月16日 09:51:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/72253479.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定