一次添加两个项目以在 for 循环中构建结构



我正在尝试一次将 2 个项目添加到结构数组中,然后每 2 个项目连续创建一个新的结构数组并附加到最终的Container结构中。我正在努力寻找正确的方法来做到这一点。

为了进一步说明我的意思:

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)
}

链接: https://play.golang.org/p/OhSntFT7Hp

我期望的行为是遍历所有commits,每次SubContainer到达len(2(时,附加到Container,并创建一个新的SubContainer,直到for循环完成。如果元素数量不均匀,则最后一个子容器将只容纳一个元素并像往常一样附加到容器。

有人对如何做到这一点有任何建议吗?抱歉,如果这是一个显而易见的答案,非常新的Go!

您可以通过将切片设置为 nil 来"重置"切片。另外,您可能不知道 nil-slices 与 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

最新更新