Home > Backend Development > Golang > Why Doesn't Go's `a[3:]` Slice Panic, But `a[4:]` Does?

Why Doesn't Go's `a[3:]` Slice Panic, But `a[4:]` Does?

Linda Hamilton
Release: 2024-12-10 08:03:10
Original
184 people have browsed it

Why Doesn't Go's `a[3:]` Slice Panic, But `a[4:]` Does?

Understanding Go's Slice Expression Behavior

In Go, slicing is a powerful mechanism for extracting specific elements from a slice, array, or string. However, certain behaviors may seem unexpected, such as the following:

a := []int{1, 2, 3}
fmt.Println(a[0:])
fmt.Println(a[1:])
fmt.Println(a[2:])
fmt.Println(a[3:]) // doesn't panic - why??
fmt.Println(a[4:]) // panics as expected
Copy after login

Why doesn't a[3:] panic?

According to the Go language specification, for array or string slices, the indices are in range if they satisfy the following condition: 0 <= low <= high <= len(a). However, for slices, the upper index bound is cap(a) rather than len(a). In this case, the underlying array has a capacity of 3, which is equal to its length.

Therefore, a[3:] doesn't panic because the upper index bound of 3 is within the valid range determined by cap(a). It results in an empty slice, as it starts at index 3 and has a length of 0 (len(a) - 3 = 0).

Why does a[4:] panic?

On the other hand, a[4:] panics because the upper index bound of 4 exceeds both len(a) and cap(a). The specification states that indices out of range at run time will lead to a runtime panic.

The above is the detailed content of Why Doesn't Go's `a[3:]` Slice Panic, But `a[4:]` Does?. 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