【问题标题】:Most idiomatic way to group structs?对结构进行分组的最惯用方式?
【发布时间】:2014-03-09 18:33:48
【问题描述】:

我正在尝试通过多个键将一组结构组合在一起。在下面的示例中,猫被分组在一起,它们的年龄和名称用作键。 Go 中是否有更惯用、通用或更好的方法来做到这一点?

我需要为多种类型的不同结构应用“分组依据”,所以这可能会变得非常冗长。

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

【问题讨论】:

    标签: go grouping


    【解决方案1】:

    这是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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多