Working with Strings
A Go string is an immutable sequence of bytes, so indexing and slicing work on bytes, changing text always builds a new string, and the strings package supplies the everyday operations.
Measure text in bytes and runes, and choose the operation that matches the task.
At its heart, tally does one thing to text: turn a line like " The cat saw THE dog " into clean, lower-case words. That needs you to know what a string really is, and which tools in the strings package do the heavy lifting.
The rule
Strings are immutable bytes; every change makes a new string.
Bytes. A string is a sequence of bytes. len(s) counts them, s[i] returns one byte, and s[a:b] slices by byte positions:
s := "tally"
fmt.Println(s[0]) // 116, the byte for 't'
fmt.Println(s[1:4]) // allImmutable. You cannot change a string in place. s[0] = 'T' is a compile error. Every operation that "changes" text — +, strings.ToUpper, strings.ReplaceAll — returns a new string and leaves the old one untouched. That makes strings safe to share and cheap to pass around.
The strings package covers the daily work:
line := " The cat saw THE dog "
words := strings.Fields(strings.ToLower(line))
fmt.Println(words) // [the cat saw the dog]
fmt.Println(len(words)) // 5| Function | Result |
|---|---|
strings.Fields(s) |
splits on any run of whitespace, no empty pieces |
strings.Split(s, ",") |
splits on exactly that separator, keeping empty pieces |
strings.TrimSpace(s) |
removes leading and trailing whitespace |
strings.Contains(s, "cat") |
true if the text appears |
strings.Join(words, " ") |
glues a slice back together |
Strings compare with == and < (byte by byte, so "Zebra" < "apple" is true — capital letters sort first).
Building text in a loop? += makes a new string every time. strings.Builder grows one buffer instead:
var b strings.Builder
for _, w := range words {
b.WriteString(w)
b.WriteString(";")
}
fmt.Println(b.String()) // the;cat;saw;the;dog;