如何将数据从一个结构体切片移动到另一个结构体切片?

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

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 = [{&quot;bob&quot;, 3, 4}, {&quot;mary&quot;, 5, 2}]	


for i:=0 ; i &lt; 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,
    }
}

所以除了你的语法错误之外,这种写法更符合惯用方式,因为:

  1. 它使用range而不是for循环,非常适合遍历数组,并且更易读。
  2. bData被预先分配了所需的确切大小。
  3. 在声明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{{&quot;bob&quot;, 3, 4}, {&quot;mary&quot;, 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:

  1. It uses range instead of a for loop, which is perfect for iterating over an array, and more readable.
  2. bData is preallocated to the exact size needed.
  3. Field names are specified in the declaration of bData's values. It would be more idiomatic to do the same for aData as well, but it gets a bit verbose.

huangapple
  • 本文由 发表于 2017年6月26日 16:45:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/44755921.html
匿名

发表评论

匿名网友

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

确定