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

Friday, May 13, 2022

[FIXED] Why append slice in Go change the original slice?

 May 13, 2022     append, go, slice     No comments   

Issue

I have this code:

// The input param is A := []int{3, 4, 5, 3, 7}
func someFunc(A []int) int {   
...
    ways := 0       
    i := 0
    for i < len(A) {
        if i+1 == len(A) || i == len(A) {
            fmt.Println("break")
            break
        }
        tempA := A // copy the slice by value

        fmt.Println("A: ", A)
        fmt.Println("tempA: ", A)
        fmt.Println()

        newArr = remove(tempA, i)

        if isAesthetic(newArr) {
            ways++
        }
        i++
    }
...
}

func remove(slice []int, s int) []int {
    return append(slice[:s], slice[s+1:]...)
}

Cosole output:

A:  [3 4 5 3 7]
tempA:  [3 4 5 3 7]

A:  [4 5 3 7 7]
tempA:  [4 5 3 7 7]

A:  [4 3 7 7 7]
tempA:  [4 3 7 7 7]

A:  [4 3 7 7 7]
tempA:  [4 3 7 7 7]

The variable A also changes while I just copy it by value into tempA. And also it is append() function, why the slice that used to append tempA also changed?


Solution

You need to utilize the copy function:

package main
import "fmt"

func main() {
   a := []int{3, 4, 5, 3, 7}
   // bad
   b := a
   // good
   c := make([]int, len(a))
   copy(c, a)
   // CHANGES b and a!
   b = append(b[:1], b[2:]...)
   // c stays the same, a is messed up
   // [3 5 3 7 7] [3 5 3 7] [3 4 5 3 7]
   fmt.Println(a, b, c)
}

https://golang.org/pkg/builtin#copy



Answered By - Zombo
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • 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