A string is a read-only sequence of bytes, conventionally used for text. Go supports Unicode by storing string contents as UTF-8, while leaving the underlying byte representation visible through operations such as len. section 3.8 section 3.8.4
Use strings with these practical rules:
- Treat len as a byte count, not a character count: ASCII characters occupy one byte, while Unicode characters can occupy one to four bytes. section 3.8.4
- Use comparison operators for byte-based ordering and equality, and use + to concatenate strings. section 3.8.3
- Avoid indexing a Unicode string as though each byte were a character; a byte-oriented loop works as expected only for ASCII. section 3.8.4
- Convert file bytes to string before applying string functions, or use equivalent functions from the bytes package. section 2.6.4
Count words in loaded text
fileContents contains raw bytes from a file. Convert them to a string, then let strings.Fields split on whitespace and discard empty chunks: words := strings.Fields(string(fileContents)). section 2.6.4
Listing 2.27 Using strings.Fields on the file contents
words := strings.Fields(string(fileContents))
Use strings.Fields after converting raw file contents from bytes to string. section 2.6.4























