golang map里的切片

新建一个map切片
myMap := make(map[int][]int)

//定义一个结构
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)
        }
    }
}

你可能感兴趣的:(golang map里的切片)