Home > Backend Development > Golang > Why Does Slicing `b[1:]` Cause an Out-of-Bounds Error in Go?

Why Does Slicing `b[1:]` Cause an Out-of-Bounds Error in Go?

Mary-Kate Olsen
Release: 2024-12-05 03:43:14
Original
765 people have browsed it

Why Does Slicing `b[1:]` Cause an Out-of-Bounds Error in Go?

Slicing: Out of Bounds Error in Go

When executing the following code:

package main

import "fmt"

func main() {
    a := make([]int, 5)
    printSlice("a", a)
    b := make([]int, 0, 5)
    printSlice("b", b)
    c := b[1:]
    printSlice("c", c)
}


func printSlice(s string, x []int) {
    fmt.Printf("%s len=%d cap=%d %v\n",
        s, len(x), cap(x), x)
}
Copy after login

you encounter an "out of bounds" error. This error occurs because of an invalid slicing expression when creating the c slice.

In Go, slicing an array or slice follows these rules:

  • Indices are in range if 0 <= low <= high <= len(a) for arrays or strings.
  • For slices, the upper index bound defaults to the slice capacity (cap(a)) instead of its length.

The slicing expression b[1:] attempts to create a new slice c with a lower bound of 1. However, the higher bound is missing and defaults to the length of b, which is 0. This results in a slice with a lower bound greater than its upper bound, leading to the "out of bounds" error.

To correct this error, you must ensure that the higher bound of the slicing expression is greater than or equal to the lower bound. For example, you could use the following expression to create a valid slice c:

c := b[1:2]
Copy after login

This creates a slice c with a lower bound of 1 and an upper bound of 2, which is valid since 1 <= 2 <= cap(b) (the capacity of b is 5).

The above is the detailed content of Why Does Slicing `b[1:]` Cause an Out-of-Bounds Error in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template