Home >Backend Development >Golang >Why Doesn't `a[len(slice)]` Panic in Go Slices?

Why Doesn't `a[len(slice)]` Panic in Go Slices?

Susan Sarandon
Susan SarandonOriginal
2024-12-12 16:40:10475browse

Why Doesn't `a[len(slice)]` Panic in Go Slices?

Go's Perplexing Slicing: Why a[len(slice)] Doesn't Panic

Introduction

In Go, when slicing an array or slice, one might expect that exceeding the length of the underlying array or slice would result in a panic. However, for slices, this behavior strangely diverges.

The Problem

Consider the following Go code:

a := []int{1, 2, 3}
fmt.Println(a[0:])
fmt.Println(a[1:])
fmt.Println(a[2:])
fmt.Println(a[3:]) // Surprisingly, doesn't panic
fmt.Println(a[4:]) // Panics as expected

perplexing that the slice a[3:] doesn't produce a panic, even though it appears to exceed the length of the array.

The Answer

This behavior is dictated by the Go language specification:

  • For arrays and strings, out-of-range indices are defined as low > len(a) or high > len(a), where a is the underlying array.
  • For slices, out-of-range indices are defined as high > cap(a), where cap(a) represents the slice's capacity.

In our example, a is an array, and its length is 3. However, splicing up to the length of the array, i.e., a[3:], is considered within the valid range because the underlying array has a length of 3.

As the specification explains, "The upper index bound is the slice capacity cap(a) rather than the length." So, in this case, a[3:] creates an empty slice because high - low = 3 - 3 = 0.

A Key Distinction

It's important to note that using an index beyond the slice's capacity (i.e., a[4:] in our example) remains out of range and will result in a runtime panic. The specification explicitly states this: "If the indices are out of range at run time, a run-time panic occurs."

The above is the detailed content of Why Doesn't `a[len(slice)]` Panic in Go Slices?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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