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

See Range expression doc here

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

See Index expression doc here

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package main

import (
"fmt"
)

func main() {
s := "H世界"
fmt.Println("Range expression on rune slice")
runes := []rune(s)
for _, r := range runes {
fmt.Println(r)
}
fmt.Println("Range expression on string")
for _, l := range s {
fmt.Println(l)
}
fmt.Println("Index expression on string")
for i := 0; i < len(s); i++ {
fmt.Println(s[i])
}
fmt.Println("------")

fmt.Println("string length: ", len(s))
fmt.Println("runes length: ", len(runes))
}

Output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Range expression on rune slice
72
19990
30028
Range expression on string
72
19990
30028
Index expression on string
72
228
184
150
231
149
140
------
string length: 7
runes length: 3