Last active
September 7, 2019 14:55
-
-
Save dimroc/2e9c0bc321c3cd78913adc93c775e80b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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("====") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://medium.com/@Jarema./golang-slice-append-gotcha-e9020ff37374
Make a new array by appending to a blank value.