Go: append directly to slice found in a map

后端 未结 1 1155
别跟我提以往
别跟我提以往 2021-01-05 01:55

I wanted to create a map of slices where values are appended to the corresponding slice. However, when trying to append directly to the slice returned by accessing it (see c

相关标签:
1条回答
  • 2021-01-05 02:32

    append returns a new slice if the underlying array has to grow to accomodate the new element. So yes, you have to put the new slice back into the map. This is no different from how strings work, for instance:

    var x map[string]string
    x["a"] = "foo"
    
    y := x["a"]
    y = "bar"
    
    // x["a"] is still "foo"
    

    To get the behaviour you expected, you'd have to use slice pointers.

    aminoAcidsToCodons := map[rune]*[]string{}
    for codon, aminoAcid := range utils.CodonsToAminoAcid {
        mappedAminoAcid := aminoAcidsToCodons[aminoAcid]
        *mappedAminoAcid = append(*mappedAminoAcid, codon)
    }
    

    That being said, since nil is a perfectly fine first argument for append, you can simplify your code to

    aminoAcidsToCodons := map[rune][]string{}
    for codon, aminoAcid := range utils.CodonsToAminoAcid {
        aminoAcidsToCodons[aminoAcid] = append(aminoAcidsToCodons[aminoAcid], codon)
    }
    
    0 讨论(0)
提交回复
热议问题