Sobes.tech
Junior — Middle

Kuidas toimub viilu pikkuse teisendamine selle tegelikuks suuruseks mälus?

sobes.tech AI

Vastus AI-lt

In Go, a slice is a structure that contains:

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

The length of the 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.

Memory size of the slice = sizeof(element) * cap.

Demonstration code:

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)))
}