doufanglian7585 2017-08-25 11:56
浏览 13
已采纳

一次添加两个项目以构造for循环

I'm trying to add 2 items at once to a struct array, then continuously every 2 items create a new struct array and append to the final Container struct. I'm struggling to find the proper way of doing this.

To further illustrate what I mean:

package main

import "fmt"

type Container struct {
    Collection []SubContainer
}

type SubContainer struct {
    Key   string
    Value int
}

func main() {
    commits := map[string]int{
        "a": 1,
        "b": 2,
        "c": 3,
        "d": 4,
        "e": 5,
        "f": 6,
    }

    sc := []SubContainer{}
    c := Container{}

    for k, v := range commits {
        sc = append(sc, SubContainer{Key: k, Value: v})
    }

    for _, s := range sc {
        c.Collection = append(c.Collection, s)
    }

    fmt.Println(c)
}

Link: https://play.golang.org/p/OhSntFT7Hp

My desired behaviour is to loop through all the commits, and every time the SubContainer reaches len(2), append to the Container, and create a new SubContainer until the for loop is complete. If there's an uneven number of elements, then the last SubContainer would just hold one element and append to Container like normal.

Does anyone have any suggestions on how to do this? Apologies if this is a obvious answer, very new to Go!

  • 写回答

1条回答 默认 最新

  • douke1891 2017-08-25 12:11
    关注

    You can "reset" a slice by setting it to nil. Also, you may not be aware that nil-slices work just fine with append:

    var sc []SubContainer
    c := Container{}
    
    for k, v := range commits {
        sc = append(sc, SubContainer{Key: k, Value: v})
        if len(sc) == 2 {
            c.Collection = append(c.Collection, sc...)
            sc = nil
        }
    }
    if len(sc) > 0 {
        c.Collection = append(c.Collection, sc...)
    
    }
    

    https://play.golang.org/p/ecj52fkwpO

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签)
  • ¥50 sft下载大文阻塞卡死
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失
  • ¥15 springboot+vue 集成keycloak sso到阿里云
  • ¥15 win7系统进入桌面过一秒后突然黑屏
  • ¥30 backtrader对于期货交易的现金和资产计算的问题
  • ¥15 求C# .net4.8小报表工具
  • ¥15 安装虚拟机时出现问题