golang-pitfalls-strings
Installation
SKILL.md
Golang Pitfalls: Strings & Bytes
Source material: mistakes #36-41 from 100 Go Mistakes and How to Avoid Them (teivah/100-go-mistakes).
Apply these rules when manipulating strings in Go.
36. Not understanding the concept of rune (#36)
- A charset is a set of characters; an encoding translates characters to binary.
- A Go string references an immutable slice of arbitrary bytes. Source-code literals are UTF-8, but strings from elsewhere may not be.
- A
runeis a Unicode code point, encoded in UTF-8 using 1 to 4 bytes. len(s)returns the number of bytes, not runes. ("hêllo"has 5 runes butlen== 6.)
37. Inaccurate string iteration (#37)
for i := range siterates over the starting byte index of each rune, not each rune.s[i]returns a single byte — printing it corrupts multi-byte runes (e.g.,êprints asÃ).- To print all runes, use the value element:
for i, r := range s { ... }. - To access the ith rune, convert to
[]rune:[]rune(s)[i]. This conversion costs O(n) — avoid it in hot loops; preferrangewith the value when iterating everything.