How do I preallocate capacity for a slice in Go?

Go, Golang, preallocate capacity, slice, programming
Learn how to preallocate capacity for slices in Go to enhance performance and efficiency in your applications.

package main

import "fmt"

func main() {
    // Preallocating capacity for a slice
    // Here we create a slice of integers with a capacity of 10
    numbers := make([]int, 0, 10)

    // Adding elements to the preallocated slice
    for i := 0; i < 10; i++ {
        numbers = append(numbers, i)
    }

    // Display the length and capacity of the slice
    fmt.Println("Slice:", numbers)
    fmt.Println("Length:", len(numbers), "Capacity:", cap(numbers))
}
    

Go Golang preallocate capacity slice programming