doucan8246326 2017-06-26 08:45
浏览 27
已采纳

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

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条回答 默认 最新

  • dpstir0081 2017-06-26 08:56
    关注

    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:

    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.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器