Sobes.tech
Junior — Middle

How does the conversion of slice length to its actual size in memory occur?

sobes.tech AI

Answer from AI

In Go, a slice is a structure that contains:

  • a pointer to an array,
  • length (len),
  • capacity (cap).

The length of a slice is the number of elements it contains, and the actual size in memory depends on the capacity and the size of the element type.

For example, if you have a slice of int (usually 8 bytes per element) with length 5 and capacity 10, then in memory, space is allocated for 10 elements (80 bytes), even though the length is 5.

Size of a slice in memory = sizeof(element) * cap.

Code for demonstration:

package main
import (
    "fmt"
    "unsafe"
)
func main() {
    s := make([]int, 5, 10)
    fmt.Println("len:", len(s))
    fmt.Println("cap:", cap(s))
    fmt.Println("size in bytes:", unsafe.Sizeof(s[0])*uintptr(cap(s)))
}
How does the conversion of slice length to its actual… - sobes.tech