cap vs len of slice in golang

前端 未结 3 1461
感动是毒
感动是毒 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 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
    

提交回复
热议问题