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

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

    报告相同问题?

    悬赏问题

    • ¥15 我用C语言easyx图形库绘制了一个3d游戏方框透视,但进入游戏时候鼠标准星对准方框边缘 鼠标光标就会弹出来这是啥情况怎样让光标对准绘制的方框点击鼠标不弹出光标好烦这样
    • ¥20 用Power Query整合的问题
    • ¥20 基于python进行多背包问题的多值编码
    • ¥15 相同型号电脑与配置,发现主板有一台貌似缺少了好多元器件似的,会影响稳定性和使用寿命吗?
    • ¥15 要求编写稀疏矩阵A的转置矩阵的算法
    • ¥15 编写满足以下要求的停车场管理程序,设停车场只有一个可停放n辆车的狭窄通道且只有一个大门可供车辆进出。
    • ¥15 C语言:数据子序列基础版
    • ¥20 powerbulider 导入excel文件,显示不完整
    • ¥15 用keil调试程序保证结果进行led相关闪烁
    • ¥15 paddle训练自己的数据loss降不下去