Unexpected slice behavior

95 views
Skip to first unread message

Roel van der Goot

unread,
Nov 7, 2025, 12:48:33 PM (4 days ago) Nov 7
to golang-nuts
package main

import "fmt"

func main() {
slice := []int{1, 2}
rest := append(slice[:0], slice[1:]...)
fmt.Printf("slice = %+v, rest = %+v\n", slice, rest)
}

Actual output:
slice = [2 2], rest = [2]
Expected output:
slice = [1 2], rest = [2]


Go 1.25.3 and 1.25.4

Am I missing something?

Ian Lance Taylor

unread,
Nov 7, 2025, 1:13:53 PM (4 days ago) Nov 7
to Roel van der Goot, golang-nuts
Please see https://go.dev/blog/slices .

Ian

Roel van der Goot

unread,
Nov 7, 2025, 3:27:57 PM (4 days ago) Nov 7
to golang-nuts
Thank you. I am sure I read that blog post before, but I didn't understand the ramifications. For performance reasons it makes sense, but it remains a bit unexpected to me that rest := append(slice[:i], slice[j:]...) and rest := slices.Delete(slice, i, j) have a side effect on slice (as documented in slices.Delete). Thank you again.
Reply all
Reply to author
Forward
0 new messages