Home > Software design >  Why slice append element not update referenced element?
Why slice append element not update referenced element?

Time:12-01

This rule is what I know about slice in Go

  • When the number of elements and the width of the capacity are the same (len(fruits) == cap(fruits)), the new element resulting from append() is the new reference.
  • When the number of elements is less than the capacity (len(fruits) < cap(fruits)), the new element is placed into the capacity range, causing all other slice elements with the same reference to change in value.

I have code like this

package main

import (
    "fmt"
)

func main() {
    //declare slice
    var fruits = []string{"banana", "mango", "tomato"}

    //using two index technique to make slice
    var newFruits = fruits[1:2]

    //append element to fruits slice
    fruits = append(fruits, "papaya")
    
    //append element to newFruits slice
    newFruits = append(newFruits, "dragon")

    fmt.Println(cap(fruits)) //2
    fmt.Println(cap(newFruits)) //6
    fmt.Println(newFruits) //[mango dragon]
    fmt.Println(fruits) //[banana mango tomato papaya]
    
}

why the value of fruits is not [banana mango dragon papaya]?

CodePudding user response:

Here's how the code works:

Just before appending papaya to fruits,

fruits = {"banana", "mango", "tomato"}

and newFruits points to the same array as fruits but starting from mango.

When you append papaya to fruits, a new array is created with capacity=6, because the capacity of fruits is 3. fruits now points to this new array, with 4 values:

fruits = {"banana", "mango", "tomato", "papaya"}

newFruits still points to the old fruits array, and contains 2 elements.

  • Related