String#

Under the covers, Go uses a sequence of bytes (uint8) to represent a string, not runes (int32).

eg.

s := "Hello, 世界"
fmt.Println(len(s)) // 13

len() returns the number of bytes, not the number of runes (which is 9 in this case).

Conversions#

Most data in Go is read and written as a sequence of bytes, so the most common string type conversions are back and forth with a slice of bytes ([]byte). Slices of runes ([]rune) are uncommon.

eg.

s := "hello"
b := []byte(s)
s2 := string(b)

Appending String to Byte Slice#

When appending a string to a []byte, using the ellipsis ... directly on the string is more efficient as it avoids an extra memory allocation.

  • s = append(s, []byte(str)...): Requires an extra allocation for the []byte conversion.
  • s = append(s, str...): No additional allocation.

for-range Loop#

Despite a string being a sequence of bytes(uint8), for-range iterates over the runes (int32), not the bytes. Whenever it encounters a multibyte rune, it converts the UTF-8 representation into a single 32-bit number.

eg.

s := "Hello, 世界"
for i, r := range s {
    fmt.Printf("%d\t%q\t%d\n", i, r, r)
}
0	'H'	72
1	'e'	101
2	'l'	108
3	'l'	108
4	'o'	111
5	','	44
6	' '	32
7	'世'	19990
10	'界'	30028

Notice that the index i might skip some values if it encounters a multibyte rune.


# go