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
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:
range
instead of a for
loop, which is perfect for iterating over an array, and more readable.bData
is preallocated to the exact size needed.bData
's values. It would be more idiomatic to do the same for aData
as well, but it gets a bit verbose.