๐Ÿ“Strings & RunesLESSON

Strings & Runes

Strings Are Byte Slices

In Go, a string is an immutable sequence of bytes โ€” specifically, UTF-8 encoded bytes. This means a string is not a sequence of characters; it is a sequence of raw bytes that happen to encode text.

The key insight: len(s) returns the byte count, not the number of visible characters. For ASCII-only strings these are equal, but for multi-byte Unicode text they are not.

Runes: Unicode Code Points

Go introduces the rune type as an alias for int32. A rune represents a single Unicode code point โ€” what most languages call a "character".

Single-quoted literals produce a rune (int32). Double-quoted literals produce a string.

Iterating: range vs index

There are two ways to iterate over a string, and they behave differently:

Range loop โ€” iterates over runes (Unicode-safe):

Notice the byte indices jump by 3 because each character occupies 3 bytes.

Index loop โ€” iterates over bytes:

Use range for text processing; use direct index access only when you are deliberately working with raw bytes.

The strings Package

The strings package covers virtually every common string operation:

strings.Fields splits on any whitespace and ignores leading/trailing spaces โ€” often more convenient than strings.Split(s, " ").

The strconv Package

strconv converts between strings and primitive types:

Always check the error return from Atoi and ParseFloat โ€” user input may not be valid.

Efficient Concatenation with strings.Builder

Concatenating strings with + inside a loop creates a new string allocation on every iteration, giving O(nยฒ) total work. strings.Builder accumulates writes into a single buffer and produces the final string with one allocation:

Use strings.Builder any time you are building a string incrementally โ€” it satisfies io.Writer, so fmt.Fprintf works directly.

Type Conversions

Go lets you convert freely between strings, byte slices, and rune slices:

Converting to []rune is the correct way to index into a string by character position rather than byte position.

Knowledge Check

What does `len("hello")` return in Go?

Which type represents a Unicode code point in Go?

What is the advantage of strings.Builder over repeated string concatenation?