Strings

Contents

Strings#

Immutable UTF-8 byte sequences. Indexing returns a byte; ranging returns (int, rune) pairs that decode code points.

Length is in bytes, not characters.

s := "héllo"
fmt.Println(len(s))          // 6 (bytes), not 5

Indexing returns a byte.

fmt.Println(s[0])            // 'h' (byte)

Ranging yields (byte index, rune) pairs that decode UTF-8.

for i, r := range s {
    fmt.Printf("%d %c\n", i, r)
}

Convert to a byte slice (mutable copy).

bs := []byte(s)

Convert to a rune slice.

rs := []rune(s)

Convert back to a string from runes.

back := string(rs)

For building strings efficiently, strings.Builder.

var b strings.Builder
for i := 0; i < 100; i++ {
    fmt.Fprintf(&b, "%d ", i)
}
out := b.String()

References#