liveBook · Manning

String

As explained in Go in Action, Second Edition

A string is Go's immutable sequence-of-bytes type, conventionally used to hold encoded text.

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

How Go in Action, Second Edition covers it

How deep it goes
Explains read-only bytes, UTF-8 encoding, comparisons, concatenation, length, and ASCII iteration, but stops short of character-level access.
Examples
Demonstrates strings.Fields, ASCII and Unicode length, hexadecimal byte output, byte iteration, comparison, escape sequences, and concatenation.
What it assumes
Assumes basic Go variables and types, while establishing strings as a foundational primitive type and distinguishing bytes from text.
What you can do after
Apply string operations and file-text processing while interpreting lengths and iteration correctly across ASCII and Unicode.
How it connects
Connects strings to Unicode, UTF-8, bytes, slices, type conversion, comparison operators, concatenation, and string manipulation.

Also explained in

Compare how 24 books explain string →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Action, Second Edition. The section links point to the parts of the book it draws on.