英文:
How to move data from one slice of structs to another?
问题
我有两个结构体:
type A struct {
Field1 string
Field2 int
Field3 int
}
type B struct {
Field1 string
Field2 int
}
我想将一个 []A
类型的切片数据(aData
)转换为一个 []B
类型的切片数据(bData
)。
有什么惯用的方法可以实现这个转换吗?
我尝试了这个方法:
var newItem B
var aData []A
var bData []B
aData = []A{{"bob", 3, 4}, {"mary", 5, 2}}
for i := 0; i < len(aData); i++ {
newItem = B{aData[i].Field1, aData[i].Field2}
bData = append(bData, newItem)
}
但是它报错:
语法错误:缺少操作数
英文:
I have two structs:
type A struct {
Field1 string
Field2 int
Field3 int
}
type B struct {
Field1 string
Field2 int
}
I want to convert a slice of []A data(aData
) to a slice of []B data (bData
).
What is the idiomatic way to do so?
What I tried is this:
var newItem B
var aData []A
var bData []B
aData = [{"bob", 3, 4}, {"mary", 5, 2}]
for i:=0 ; i < len(aData); i++ {
newItem = {aData[i].Field1, aData[i].Field2}
bData = append( bData, newItem )
}
But it gives:
> syntax error: missing operand
答案1
得分: 4
首先,你的代码是无效的。在声明aData
时,你需要一个有效的数组表达式,并且在赋值给bData
时需要指定类型。
aData := []A{{"bob", 3, 4}, {"mary", 5, 2}}
bData := make([]B, len(aData))
for i, aItem := range aData {
bData[i] = B{
Field1: aItem.Field1,
Field2: aItem.Field2,
}
}
所以除了你的语法错误之外,这种写法更符合惯用方式,因为:
- 它使用
range
而不是for
循环,非常适合遍历数组,并且更易读。 bData
被预先分配了所需的确切大小。- 在声明
bData
的值时指定了字段名。在aData
中也这样做会更符合惯用方式,但会变得有点冗长。
英文:
First, your code is invalid. You need a valid array expression for your aData
declaration, and you need to specify the type when assigning to bData
.
aData := []A{{"bob", 3, 4}, {"mary", 5, 2}}
bData := make([]B, len(aData))
for i, aItem := range aData {
bData[i] = B{
Field1: aItem.Field1,
Field2: aItem.Field2,
}
}
So aside from your syntax errors, this is more idiomatic because:
- It uses
range
instead of afor
loop, which is perfect for iterating over an array, and more readable. bData
is preallocated to the exact size needed.- Field names are specified in the declaration of
bData
's values. It would be more idiomatic to do the same foraData
as well, but it gets a bit verbose.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论