cap vs len of slice in golang

前端 未结 3 1458
感动是毒
感动是毒 2021-01-31 15:35

What is the difference between cap and len of a slice in golang?

According to definition:

A slice has both a length and a capacity.

The length of a slice

相关标签:
3条回答
  • 2021-01-31 15:54

    You've answered your question - the length of the underlying array in a slice is not necessarily the same as the number of elements that array contains.

    0 讨论(0)
  • 2021-01-31 16:08

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

    cap tells you the capacity of the underlying array. len tells you how many items are in the array.

    The slice abstraction in Go is very nice since it will resize the underlying array for you, plus in Go arrays cannot be resized so slices are almost always used instead.

    Example:

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

    Will output something like this:

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

    As you can see once the capacity is met, append will return a new slice with a larger capacity. On the 4th iteration you will notice a larger capacity and a new pointer address.

    Play example

    I realize you did not ask about arrays and append but they are pretty foundational in understanding the slice and the reason for the builtins.

    0 讨论(0)
  • 2021-01-31 16:15

    From the source code:

    // 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
    
    0 讨论(0)
提交回复
热议问题