Home > Backend Development > Golang > Why does Go throw a \'panic: runtime error: index out of range\' error when working with slices even if the array length is non-zero?

Why does Go throw a \'panic: runtime error: index out of range\' error when working with slices even if the array length is non-zero?

DDD
Release: 2024-10-29 09:29:29
Original
411 people have browsed it

Why does Go throw a

Go "panic: runtime error: index out of range" When Array Length Is Non-Zero

In Go, when working with strings, you may encounter an "index out of range" runtime error while attempting to loop through them. This issue can arise even when the underlying array is not empty. To resolve it, we need to understand the nuances of slice allocation and appendation.

Slices and Their Internals

Slices in Go represent a segment of an array with a pointer, a length, and a capacity. When creating a slice using make([]string, 0, 4), we specify a length of 0 and a capacity of 4. This means the underlying array is empty, and accessing elements directly will result in a runtime error.

In contrast, make([]string, 4) allocates an array with 4 elements, initializing them with empty strings. Therefore, accessing elements within this slice is safe without triggering an error.

The append Function

The append function extends the length of a slice by appending elements to it. If the slice has enough capacity, it will resize the underlying array to accommodate the new elements. However, if the capacity is insufficient, a new array is created.

In the given code snippet, the result slice is initially empty. When using append within the loop to add elements, it attempts to access the slice at an index that exceeds the current length, causing the runtime error.

Resolution

To resolve this issue, ensure the result slice has a non-zero length before accessing elements within the loop. This can be achieved by allocating the slice with an initial length or using append in a modified way.

Consider the following code snippet:

<code class="go">package main

import "fmt"
import "strings"

func myFunc(input string) []string {
    strs := strings.Fields(input)  // Extract words from the input string
    result := make([]string, 0, 4) // Initialize an empty slice with a capacity of 4
    for _, s := range strs {
        if strings.ContainsAny(s, "eaiu") { // Check if the word contains a vowel
            result = append(result, s) // Append the word to the slice
        }
    }
    return result
}

func main() {
    fmt.Println(myFunc("Political"))
}</code>
Copy after login

In this code, make([]string, 0, 4) initializes an empty slice with a capacity of 4. Then, the loop iterates over each word in the input string and appends it to the result slice if it contains a vowel. The append function is used correctly, as the loop ensures the slice has a non-zero length before accessing elements.

The above is the detailed content of Why does Go throw a \'panic: runtime error: index out of range\' error when working with slices even if the array length is non-zero?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template