Search code examples
gohashmap

How to assign a slice to a hashmap


I am trying to make a hash map containing keys like "cow", "bird", etc. and to each key, I want to assign a slice.

I am unable to understand how I should go about this, and even if I created it how to append to such slice.


Solution

  • I think you are looking for something like this

        animalMap := make(map[string][]string, 0)
    
        animalMap["cow"] = []string{"Alice", "Bob"}
        animalMap["bird"] = []string{"Tweety", "Sam"}
    
        fmt.Printf("%v\n", animalMap)
    
        // Appending value to existing slice for "cow"
        animalMap["cow"] = append(animalMap["cow"], "Chris")
    
        // Appending value to existing slice for "bird"
        animalMap["bird"] = append(animalMap["bird"], "Tom")
    
        fmt.Printf("%v\n", animalMap)
    
    

    Here's the live example: https://play.golang.org/p/YXS-IlWUPfi