Home  >  Article  >  Backend Development  >  Why Does Appending to a Slice Found in a Go Map Require Reassignment?

Why Does Appending to a Slice Found in a Go Map Require Reassignment?

Barbara Streisand
Barbara StreisandOriginal
2024-11-05 06:41:02311browse

Why Does Appending to a Slice Found in a Go Map Require Reassignment?

Appending Directly to Slice Found in a Go Map

Directly appending to a slice retrieved from a map can be a tricky task to understand. Let's dive into the issue and its solution.

In the provided code, an attempt was made to append to a slice stored in a map:

<code class="go">mappedAminoAcid, ok := aminoAcidsToCodons[aminoAcid]
if ok {
    // NOT WORKING: mappedAminoAcid = append(mappedAminoAcid, codon)
    aminoAcidsToCodons[aminoAcid] = append(mappedAminoAcid, codon)
}</code>

However, this failed because append returns a new slice if the underlying array needs to grow. Therefore, it's necessary to assign the new slice back to the map entry.

Here's why directly assigning doesn't work:

When a slice is returned by a function or accessed from a map, it's a copy of the original slice, not a pointer. Modifications made to the copy are not reflected in the original.

For example, consider a string:

<code class="go">x := "foo"
y := x
y = "bar"
fmt.Println(x) // "foo" (unchanged)</code>

Since a nil slice is acceptable as an initial argument to append, the code can be simplified:

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

In summary, when appending to a slice retrieved from a map, it's crucial to remember that the returned slice is a copy, and to assign the new slice back to the map entry.

The above is the detailed content of Why Does Appending to a Slice Found in a Go Map Require Reassignment?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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