Home > Backend Development > Golang > What is the capacity and length of a slice in Go?

What is the capacity and length of a slice in Go?

James Robert Taylor
Release: 2025-03-19 12:19:32
Original
235 people have browsed it

What is the capacity and length of a slice in Go?

In Go, a slice is a flexible and powerful data structure that is built on top of an array. It has two key properties: length and capacity.

  • Length: The length of a slice is the number of elements it contains. It represents the size of the slice that you can access directly. You can obtain the length of a slice using the len() function.
  • Capacity: The capacity of a slice is the maximum number of elements the slice can hold without allocating new memory. It represents the total space allocated for the underlying array. You can get the capacity of a slice using the cap() function.

Here is a simple example demonstrating the use of len() and cap():

package main

import "fmt"

func main() {
    s := make([]int, 5, 10) // Creates a slice with length 5 and capacity 10
    fmt.Printf("Length: %d, Capacity: %d\n", len(s), cap(s))
}
Copy after login

In this example, the slice s has a length of 5 and a capacity of 10.

How can I modify the capacity of a slice in Go?

The capacity of a slice in Go is immutable once it is created. You cannot directly modify the capacity of an existing slice. However, you can create a new slice with a different capacity using a few methods:

  1. Using the make function: You can create a new slice with a specified length and capacity.

    newSlice := make([]int, len(oldSlice), newCapacity)
    copy(newSlice, oldSlice)
    Copy after login
    Copy after login
  2. Using the append function: When you append elements to a slice, Go will automatically increase the capacity if necessary.

    s := []int{1, 2, 3}
    s = append(s, 4, 5, 6) // This might increase the capacity if needed
    Copy after login
  3. Using the copy function: You can copy the contents of the old slice to a new slice with a different capacity.

    newSlice := make([]int, len(oldSlice), newCapacity)
    copy(newSlice, oldSlice)
    Copy after login
    Copy after login

Here’s an example to illustrate these methods:

package main

import "fmt"

func main() {
    s := []int{1, 2, 3} // Length: 3, Capacity: 3
    fmt.Printf("Original: Length: %d, Capacity: %d\n", len(s), cap(s))

    // Using make and copy
    newSlice := make([]int, len(s), 10)
    copy(newSlice, s)
    fmt.Printf("After make and copy: Length: %d, Capacity: %d\n", len(newSlice), cap(newSlice))

    // Using append
    s = append(s, 4, 5, 6, 7)
    fmt.Printf("After append: Length: %d, Capacity: %d\n", len(s), cap(s))
}
Copy after login

What happens when I try to access an index beyond the length of a slice in Go?

In Go, attempting to access an index beyond the length of a slice will result in a runtime panic. This is because the length of the slice defines the range of indices you can safely access.

Here’s an example:

package main

import "fmt"

func main() {
    s := []int{1, 2, 3} // Length: 3
    fmt.Println(s[0])   // This is valid
    fmt.Println(s[3])   // This will cause a runtime panic
}
Copy after login

The error message you would see is something like this:

<code>panic: runtime error: index out of range [3] with length 3</code>
Copy after login

This panic occurs because index 3 is outside the bounds of the slice, whose length is 3.

What is the difference between the length and capacity of a slice in Go?

The length and capacity of a slice in Go serve different purposes and have different roles:

  • Length: The length of a slice is the number of elements it currently holds. It determines the valid indices of the slice. You can access elements of the slice up to len(s) - 1, and attempting to access an index beyond this will result in a runtime panic.
  • Capacity: The capacity of a slice is the total number of elements the underlying array can hold. It defines the maximum potential length the slice can reach without needing to allocate new memory. You can increase the length of the slice up to the capacity using the append function without triggering memory reallocation.

Here’s a summary of their differences:

  • Length:

    • Defines the current number of elements in the slice.
    • Accessed via len(s).
    • Determines the range of valid indices.
  • Capacity:

    • Defines the maximum number of elements the underlying array can hold.
    • Accessed via cap(s).
    • Indicates the potential growth of the slice without memory reallocation.

Here is an example illustrating these concepts:

package main

import "fmt"

func main() {
    s := make([]int, 3, 5) // Length: 3, Capacity: 5
    fmt.Printf("Initial: Length: %d, Capacity: %d\n", len(s), cap(s))

    s = append(s, 4) // Length: 4, Capacity: 5
    fmt.Printf("After first append: Length: %d, Capacity: %d\n", len(s), cap(s))

    s = append(s, 5) // Length: 5, Capacity: 5
    fmt.Printf("After second append: Length: %d, Capacity: %d\n", len(s), cap(s))

    s = append(s, 6) // Length: 6, Capacity might increase
    fmt.Printf("After third append: Length: %d, Capacity: %d\n", len(s), cap(s))
}
Copy after login

In this example, the slice starts with a length of 3 and a capacity of 5. As we append elements, the length increases until it reaches the capacity. The capacity may increase when we exceed the original capacity.

The above is the detailed content of What is the capacity and length of a slice in Go?. For more information, please follow other related articles on the PHP Chinese website!

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