Created
August 23, 2025 15:35
-
-
Save lechuhuuha/6aa1de34e424665c1df2525646323dac to your computer and use it in GitHub Desktop.
slice pitfall
This file contains hidden or 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() { | |
| a := [5]int{1, 2, 3, 4, 5} | |
| s1 := a[0:3] // len=3 cap=5 | |
| s2 := a[3:5] // len=2 cap=2 | |
| fmt.Println("initial a :", a) // [1 2 3 4 5] | |
| fmt.Println("initial s1 :", s1) // [1 2 3 4 5] | |
| fmt.Println("initial s2 :", s2) // [4 5] | |
| s1 = append(s1, 100) // within cap → overwrites a[3] | |
| fmt.Println("\nafter append(s1,100):") | |
| fmt.Println("s1 :", s1) // [1 2 3 100 5] | |
| fmt.Println("a :", a) // [1 2 3 100 5] | |
| fmt.Println("s2 :", s2) // [100 5] ← overwritten! | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment