Member-only story
Working with Strings in Go: A Practical Guide to unicode, strings, and strconv
How to inspect characters, transform text, and turn user input into usable numbers.
A user enters " 123 " into a form. Your application receives text, but the next operation needs a number. Somewhere else, you need to uppercase a name, check a filename, or recognize a letter with an accent.
These are small tasks, but they sit at the boundary between external input and application logic. Go provides three standard library packages that make them straightforward: unicode, strings, and strconv.
Before using them, it helps to understand what a Go string actually contains.
A string is an immutable sequence of bytes. It can contain arbitrary bytes, although ordinary text is commonly encoded as UTF-8. A rune represents a Unicode code point. That distinction explains this result:
text := "čau"
fmt.Println(len(text)) // 4
fmt.Println(len([]rune(text))) // 3The Czech letter č takes two bytes in UTF-8. The other two letters take one each.
Indexing a string accesses a byte. Iterating with range decodes runes and reports their starting byte positions:
for index, r := range "čau" {
fmt.Printf("%d: %c\n", index, r)
}
// 0: č
// 2: a
//…







