Skip to content

Instantly share code, notes, and snippets.

@dimroc
Last active September 7, 2019 14:55
Show Gist options
  • Save dimroc/2e9c0bc321c3cd78913adc93c775e80b to your computer and use it in GitHub Desktop.
Save dimroc/2e9c0bc321c3cd78913adc93c775e80b to your computer and use it in GitHub Desktop.
package main
import "fmt"
func main() {
fmt.Println("append gotcha\n")
// not copying
arr1 := []int{1, 2, 3}
for i, _ := range arr1 {
fmt.Println("prefix: ", arr1[:i])
fmt.Println("suffix: ", arr1[i+1:])
cp := append(arr1[:i], arr1[i+1:]...)
fmt.Println("arr1: ", arr1)
fmt.Println("cp: ", cp)
fmt.Println("====")
}
fmt.Println("when copying\n")
// copying
arr1 = []int{1, 2, 3}
for i, _ := range arr1 {
fmt.Println("prefix: ", arr1[:i])
fmt.Println("suffix: ", arr1[i+1:])
cp := append([]int{}, arr1[:i]...)
cp = append(cp, arr1[i+1:]...)
fmt.Println("arr1: ", arr1)
fmt.Println("cp: ", cp)
fmt.Println("====")
}
}
@dimroc
Copy link
Author

dimroc commented Sep 7, 2019

https://medium.com/@Jarema./golang-slice-append-gotcha-e9020ff37374

Make a new array by appending to a blank value.

use append only to append new value to given slice, not to create new one:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment