Accessing elements outside slice using [:]

162 views
Skip to first unread message

Pyrode

unread,
Jan 25, 2025, 12:21:25 PMJan 25
to golang-nuts
Hey,

The following code allows elements outside the length of the slice to be accessed.
Is this the expected behaviour or a bug?

Thanks
```
package main

import "fmt"

func main() {
foo([]int{1, 2, 3, 4}[0:1])
}

func foo(bar []int) {
fmt.Println(len(bar)) // Output: 1
fmt.Println(bar[0:3]) // Output: [1,2,3]
}
```

Sean Liao

unread,
Jan 25, 2025, 12:55:41 PMJan 25
to golang-nuts

> For slices, the upper index bound is the slice capacity cap(a) rather than the length.

- sean

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion visit https://groups.google.com/d/msgid/golang-nuts/71c52f83-a956-449d-8e5b-adf1a9ebfbb4n%40googlegroups.com.

Reto

unread,
Jan 25, 2025, 1:00:20 PMJan 25
to Pyrode, golang-nuts
On Fri, Jan 24, 2025 at 11:57:14PM -0800, Pyrode wrote:
> The following code <https://go.dev/play/p/P2gPMHKuJW8> allows elements
> outside the length of the slice to be accessed.
> Is this the expected behaviour or a bug?

This is expected.
They still share the same underlying data array after all.

https://go.dev/blog/slices-intro might be insightful for you.

If you want to prevent that, return a copy or truncate the cap.
slices.Clip / slices.Clone are helpful there, depending on what
constraints you need.

Pyrode

unread,
Jan 26, 2025, 6:31:47 AMJan 26
to golang-nuts
Got it 👍

Thanks for the response!
Reply all
Reply to author
Forward
0 new messages