Middle
What is the size of a slice in bytes?
sobes.tech AI
Answer from AI
The size of a slice in bytes depends on three factors:
- Slice descriptor: This is a fixed size of 24 bytes (3 pointers of 8 bytes each on a 64-bit architecture), containing a pointer to the underlying array, length, and capacity of the slice.
- Element size: The weight of each element in the underlying array.
- Slice length: The number of elements in the slice.
The total size can be approximately calculated using the formula:
Size of slice ≈ 24 bytes + (element size * slice length)
Example:
// Slice of int, where int takes 8 bytes (on a 64-bit system)
s := make([]int, 10) // Length 10
// Approximate size: 24 bytes (descriptor) + (8 bytes/element * 10 elements) = 24 + 80 = 104 bytes
It is important to remember that this is an approximate calculation and may vary depending on architecture and specific data structure of elements. The underlying array can be shared among multiple slices, affecting their independent size.