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 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?