Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang sub slice

Tags:

arrays

slice

go

In Go, why does this code work:

package main

import (
  "fmt"
)

func main() {
  a := []int{1}
  a = a[1:]
  fmt.Println(len(a))
}

but this doesn't:

package main

import (
  "fmt"
)

func main() {
  a := []int{1}
  a = a[2:]
  fmt.Println(len(a))
}

I've heard about capacity in slices, can someone elaborate it?

like image 510
Jake Muller Avatar asked Jan 23 '26 06:01

Jake Muller


1 Answers

The Go specification contains the answer to both of your questions:

Slice expressions

Slice expressions construct a substring or slice from a string, array, pointer to array, or slice. There are two variants: a simple form that specifies a low and high bound, and a full form that also specifies a bound on the capacity.

Simple slice expressions

[snippage]

For arrays or strings, the indices are in range if 0 <= low <= high <= len(a), otherwise they are out of range.

Since len(a) is 1, the index 1 is in range, but the index 2 is out of range.

Full slice expressions

For an array, pointer to array, or slice a (but not a string), the primary expression

a[low : high : max]

constructs a slice of the same type, and with the same length and elements as the simple slice expression a[low : high]. Additionally, it controls the resulting slice's capacity by setting it to max - low. Only the first index may be omitted; it defaults to 0. ...

Read the entire spec. It can be a bit slow going, but it's not all that long. There's no need to memorize it all, but having gone through the whole thing once, you should be able to remember that you read that somewhere, and then go back and find what you are looking for.

like image 104
torek Avatar answered Jan 24 '26 20:01

torek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!