Reputation: 12675
I was searching for memory allocations of slices whether static at compile time or dynamic on fly. Since slices are pointers to the array in back and I have studied that for dynamic memory allocation, pointers are crucial. So what is the allocation of slice and how about maps.
Upvotes: 2
Views: 2689
Reputation: 166569
type slice struct {
array unsafe.Pointer
len int
cap int
}
The slice descriptor is a struct
. make([]type, len, cap)
returns a slice
descriptor with a pointer to an underlying array with the given type
, len
(length), and cap
(capacity). The slice descriptor and/or its underlying array are allocated on the stack and/or the heap.
type string struct {
array unsafe.Pointer
len int
}
The string descriptor is a struct
with a pointer to an underlying byte
array with length len
. Since strings
are immutable, the capacity is redundant; it is always equal to the length. The string descriptor, from a literal or conversion, and/or its underlying array are allocated on the stack and/or the heap.
Consider a string as a special form of a byte
slice. For example, slice expressions apply to both.
The Go Programming Language Specification
Slice expressions construct a substring or slice from a string, array, pointer to array, or slice. There are two variants: a simple form that specifies a low and high bound, and a full form that also specifies a bound on the capacity.
Upvotes: 2