Stage 1 · Code
Arrays & Strings
Strings
Bytes, runes, UTF-8 encoding — Go's unique approach to text.
String Basics
In Go, a string is an immutable sequence of bytes. It's a read-only slice of bytes with syntactic support. Strings can contain arbitrary bytes, not just UTF-8.
Bytes vs Runes
Rune is Go's term for a Unicode code point (int32). A character may be 1-4 bytes in UTF-8. Use range to iterate runes, or []rune(s) to convert.
Common String Operations
| Operation | Function/Method | Example |
|---|---|---|
| Length (bytes) | len(s) | len("hi") == 2 |
| Length (runes) | utf8.RuneCountInString(s) | utf8.RuneCountInString("世") == 1 |
| Contains | strings.Contains(s, substr) | strings.Contains("hello", "ll") |
| Has prefix/suffix | strings.HasPrefix/HasSuffix | |
| Index of substr | strings.Index(s, substr) | |
| Replace | strings.ReplaceAll(s, old, new) | |
| Split | strings.Split(s, sep) | |
| Join | strings.Join(slice, sep) | |
| Trim | strings.TrimSpace(s) | Trim(s, cutset) |
| Case | strings.ToLower/ToUpper | |
| Builder | strings.Builder |
Efficient String Building
String concatenation with + creates new strings each time (O(n²) for n concatenations). Use strings.Builder for O(n) building.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.