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 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据