Home > Backend Development > Golang > How to Avoid \'Slice Bounds Out of Range\' Errors When Slicing in Go?

How to Avoid \'Slice Bounds Out of Range\' Errors When Slicing in Go?

Linda Hamilton
Release: 2024-12-04 00:21:09
Original
308 people have browsed it

How to Avoid

Slicing in Go: Understanding Out of Bounds Errors

When slicing a slice in Go, it's essential to adhere to specific bounds to avoid errors. One such error is the "slice bounds out of range" error. This error occurs when the slice expression results in indices that fall outside the allowable range.

In the code snippet provided:

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

The error occurs when trying to create the c slice with the expression c := b[1:]. This error arises not due to the lower bound (which can be equal to or greater than the length), but rather the higher bound.

In Go, the default higher bound for slicing is the length of the sliced operand. However, in this case, the sliced operand b has a length of 0. Therefore, the default higher bound becomes 0. Consequently, the expression c := b[1:] results in a lower bound of 1 and a higher bound of 0.

This violates the slicing rule which states that for slices, the indices must satisfy the following condition:

0 <= low <= high <= cap(a)
Copy after login

Where:

  • low is the lower bound
  • high is the higher bound
  • cap(a) is the capacity of the sliced operand

In this case, since 1 is not less than or equal to 0, the expression results in an out of bounds error.

To resolve this issue, explicit bounds must be specified when slicing. For example:

c := b[1:1]        // Slice from index 1 to 1 (empty slice)
c := b[1:2]        // Slice from index 1 to 2 (contains the element at index 1)
c := b[1:cap(b)]   // Slice from index 1 to the capacity of the operand (contains all elements)
Copy after login

The above is the detailed content of How to Avoid \'Slice Bounds Out of Range\' Errors When Slicing 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