PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, May 12, 2022

[FIXED] Why slice append element not update referenced element?

 May 12, 2022     append, go, slice     No comments   

Issue

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]?


Solution

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.



Answered By - Burak Serdar
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing