Skip to content

Instantly share code, notes, and snippets.

@ObsidianCat
Created June 28, 2023 15:38
Show Gist options
  • Save ObsidianCat/e154e6d8e108dc4c85a33ac47e5ecb3b to your computer and use it in GitHub Desktop.
Save ObsidianCat/e154e6d8e108dc4c85a33ac47e5ecb3b to your computer and use it in GitHub Desktop.
Unexpected behaviour of slices, when passed as argument in a function and mutated
package main
import (
"fmt"
)
func sliceExtender(sl []int) {
sl = append(sl, 33)
sl[0] = 5
fmt.Printf("len %d, cap %d, sliceOne[0]=%d, added last elemnt =%d \n", len(sl), cap(sl), sl[0], sl[len(sl)-1])
}
func main() {
sliceOne := make([]int, 1, 10)
sliceOne[0] = 1
fmt.Println("SliceOne created")
fmt.Printf("len %d, cap %d, sliceOne[0]=%d \n", len(sliceOne), cap(sliceOne), sliceOne[0])
fmt.Println("SliceOne in function")
sliceExtender(sliceOne)
fmt.Println("SliceOne in main")
fmt.Printf("len %d, cap %d, sliceOne[0]=%d, added last elemnt =%d \n", len(sliceOne), cap(sliceOne), sliceOne[0], sliceOne[len(sliceOne)-1])
fmt.Println("--------------------------------------------------")
sliceTwo := make([]int, 10)
sliceTwo[0] = 1
fmt.Println("SliceTwo created")
fmt.Printf("len %d, cap %d, SliceTwo[0]=%d \n", len(sliceTwo), cap(sliceTwo), sliceTwo[0])
fmt.Println("SliceTwo in function")
sliceExtender(sliceTwo)
fmt.Println("SliceTwo in main")
fmt.Printf("len %d, cap %d, SliceTwo[0]=%d, added last elemnt =%d \n", len(sliceTwo), cap(sliceTwo), sliceTwo[0], sliceTwo[len(sliceTwo)-1])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment