Cap against len ​​slices in golang

What is the difference between cap and golang cut line?

According to the definition:

The slice has both length and capacity.

The length of the cut is the number of elements contained in it.

Slice capacity is the number of elements in the base array, counting from the first element in the slice.

x := make([]int, 0, 5) // len(b)=0, cap(b)=5

Does len only mean nonzero values?

+19
source share
4 answers

A slice is an abstraction that uses an array under covers.

capindicates the capacity of the underlying array. lenreports how many elements are in the array.

Go , , Go , .

:

s := make([]int, 0, 3)
for i := 0; i < 5; i++ {
    s = append(s, i)
    fmt.Printf("cap %v, len %v, %p\n", cap(s), len(s), s)
}

- :

cap 3, len 1, 0x1040e130
cap 3, len 2, 0x1040e130
cap 3, len 3, 0x1040e130
cap 8, len 4, 0x10432220
cap 8, len 5, 0x10432220

, , append . 4- .

, , .

+49

:

// The len built-in function returns the length of v, according to its type:
//  Array: the number of elements in v.
//  Pointer to array: the number of elements in *v (even if v is nil).
//  Slice, or map: the number of elements in v; if v is nil, len(v) is zero.
//  String: the number of bytes in v.
//  Channel: the number of elements queued (unread) in the channel buffer;
//  if v is nil, len(v) is zero.
func len(v Type) int

// The cap built-in function returns the capacity of v, according to its type:
//  Array: the number of elements in v (same as len(v)).
//  Pointer to array: the number of elements in *v (same as len(v)).
//  Slice: the maximum length the slice can reach when resliced;
//  if v is nil, cap(v) is zero.
//  Channel: the channel buffer capacity, in units of elements;
//  if v is nil, cap(v) is zero.
func cap(v Type) int
+2

: , .

0

@jmaloney

.

osboxes@robuntu:~/go/src/hello$ ./hello 
cap 3, len 1, 0xc000016460
cap 3, len 2, 0xc000016460
cap 3, len 3, 0xc000016460
cap 6, len 4, 0xc00001a240
cap 6, len 5, 0xc00001a240
0

Source: https://habr.com/ru/post/1014119/


All Articles