go语言学习--go中的map切片

//定义一个结构
type Car struct {
    Brand string
    Age int
}

func Pluck() map[int][]Car {
    carMap := make(map[int][]Car)
    carArr := make([]Car, 0)
    carArr = append(carArr, Car{
        Brand: "audi",
        Age: 1,
    })
    carMap[1] = carArr
    //如果存在键,则添追加数据
    child, ok := carMap[1]
    if ok {
        child = append(child, Car{
            Brand:"QQ",
            Age:5,
        })
        carMap[1] = child
    } else {//第一次添加数据
        carArr := make([]Car, 0)
        carArr = append(carArr, Car{
            Brand: "audi",
            Age: 1,
        })
        carMap[1] = carArr
    }
    return carMap
}
func main() {
    rs := Pluck()
    for _, item := range rs {
        for _, child := range item {
            fmt.Println(child.Brand)
        }
    }
}

  

posted on 2019-03-10 18:08  ZhanLi  阅读(257)  评论(0编辑  收藏  举报