builtin function: len(v Type) int
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.
What is rune
rune is an alias for int32 and is equivalent to int32 in all ways. It is used, by convention, to distinguish character values from integer values.
Representing Unicode code points.
type rune = int32
What is `string
string is the set of all strings of 8-bit bytes, conventionally but not necessarily representing UTF-8-encoded text. A string may be empty, but not nil. Values of string type are immutable.
type string string
Range expression on a string
For a string value, the “range” clause iterates over the Unicode code points in the string starting at byte index 0.
- On successive iterations, the index value will be the index of the first byte of successive UTF-8-encoded code points in the string,
- and the second value, of type
rune
, will be the value of the corresponding code point.
If the iteration encounters an invalid UTF-8 sequence, the second value will be 0xFFFD, the Unicode replacement character, and the next iteration will advance a single byte in the string.
Index expression on a string
a[x]
is the non-constant byte value at index x and the type of a[x] is byte
Difference between len([]rune(s)) and len(s)
rune[]
splits string into four-byte characters; len(s) counts how many bytes are in the string.
Example
1 | package main |
Output:
1 | Range expression on rune slice |