Home > Backend Development > Golang > Why Can't I Append Directly to a Slice in a Go Map?

Why Can't I Append Directly to a Slice in a Go Map?

Susan Sarandon
Release: 2024-11-07 14:38:02
Original
820 people have browsed it

Why Can't I Append Directly to a Slice in a Go Map?

Go: Why Can't I Append Directly to a Slice Found in a Map?

In Go, when working with maps, you may encounter a situation where you need to append values to an existing slice within the map. However, attempting to append directly to the slice returned by accessing it may result in the changes not being stored.

To illustrate this issue, consider the following code fragment:

<code class="go">aminoAcidsToCodons := map[rune][]string{}
for codon, aminoAcid := range utils.CodonsToAminoAcid {
    mappedAminoAcid := aminoAcidsToCodons[aminoAcid] // Returning a copy of the slice
                                                  // instead of a reference

    // Not working: mappedAminoAcid = append(mappedAminoAcid, codon)

    aminoAcidsToCodons[aminoAcid] = append(mappedAminoAcid, codon) // Using long-form access
}</code>
Copy after login

In the commented line, an attempt is made to append directly to the slice returned by aminoAcidsToCodons[aminoAcid]. However, this operation fails since what is returned is a copy of the slice, not a reference to the slice in the map.

The reason for this behavior lies in the way append works in Go. When the capacity of the underlying array of a slice is exceeded, append creates a new slice and copies the existing elements into it. This new slice is then returned, while the original slice remains unchanged.

Therefore, to successfully append to a slice in a map, you must assign the result of the append operation back to the corresponding key in the map. This can be simplified further by using a nil slice as the first argument to append, as seen in the following modified code:

<code class="go">aminoAcidsToCodons := map[rune][]string{}
for codon, aminoAcid := range utils.CodonsToAminoAcid {
    aminoAcidsToCodons[aminoAcid] = append(aminoAcidsToCodons[aminoAcid], codon)
}</code>
Copy after login

The above is the detailed content of Why Can't I Append Directly to a Slice in a Go Map?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template