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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀