最常用的组合结构方式?

时间:2014-03-09 18:33:48

标签: go grouping

我试图通过多个键将一组结构组合在一起。在下面的示例中,猫被分组在一起,其年龄和名称被用作关键字。 Go是否有更惯用,通用或更好的方法?

我需要申请" group by"对于多种类型的不同结构,所以这可能会非常冗长。

http://play.golang.org/p/-CHDQ5iPTR

package main

import (
    "errors"
    "fmt"
    "math/rand"
)

type Cat struct {
    CatKey
    Kittens int
}

type CatKey struct {
    Name string
    Age  int
}

func NewCat(name string, age int) *Cat {
    return &Cat{CatKey: CatKey{Name: name, Age: age}, Kittens: rand.Intn(10)}
}

func GroupCatsByNameAndAge(cats []*Cat) map[CatKey][]*Cat {
    groupedCats := make(map[CatKey][]*Cat)
    for _, cat := range cats {
        if _, ok := groupedCats[cat.CatKey]; ok {
            groupedCats[cat.CatKey] = append(groupedCats[cat.CatKey], cat)
        } else {
            groupedCats[cat.CatKey] = []*Cat{cat}
        }
    }

    return groupedCats
}

func main() {
    cats := []*Cat{
        NewCat("Leeroy", 12),
        NewCat("Doofus", 14),
        NewCat("Leeroy", 12),
        NewCat("Doofus", 14),
        NewCat("Leeroy", 12),
        NewCat("Doofus", 14),
        NewCat("Leeroy", 12),
        NewCat("Doofus", 14),
        NewCat("Leeroy", 12),
        NewCat("Doofus", 14),
    }

    groupedCats := GroupCatsByNameAndAge(cats)

    Assert(len(groupedCats) == 2, "Expected 2 groups")
    for _, value := range groupedCats {
        Assert(len(value) == 5, "Expected 5 cats in 1 group")
    }

    fmt.Println("Success")
}

func Assert(b bool, msg string) {
    if !b {
        panic(errors.New(msg))
    }
}

1 个答案:

答案 0 :(得分:2)

这是GroupCatsByNameAndAge函数的更惯用的版本。请注意,如果groupedCats没有cat.CatKey,那么groupedCats[cat.CatKey]将为nil,但nilappend完全可接受的值。 Playground

func GroupCatsByNameAndAge(cats []*Cat) map[CatKey][]*Cat {
    groupedCats := make(map[CatKey][]*Cat)
    for _, cat := range cats {
        groupedCats[cat.CatKey] = append(groupedCats[cat.CatKey], cat)
    }
    return groupedCats
}
相关问题