英文:
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
Book1
和Book2
是不同类型的,即使它们具有相同的成员。你不能将[]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)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论