liveBook · Manning

Substring

As explained in 100 Go Mistakes and How to Avoid Them

A substring is a contiguous portion of a string obtained through a string operation such as slicing.

A substring is a contiguous portion of a string produced by an operation such as slicing. A common mistake is assuming log[:36] creates an independent 36-byte string. Go's standard compiler may let the substring share the original string's backing array, so retaining a short substring can keep a much larger log message in memory. section 5.6

s1 := "Hello, World!"
s2 := s1[:5] // Hello

Use byte slicing when the requested boundaries are byte boundaries, as with ASCII text or a known byte-length prefix. section 5.6

s1 := "Hêllo, World!"
s2 := string([]rune(s1)[:5]) // Hêllo

Use []rune conversion when selecting by character position, because slicing a string counts bytes rather than runes. section 5.6

Avoid retaining a heavy log

A handler that stores uuid := log[:36] may retain the entire, potentially thousands-of-bytes log. Copy the substring before storing it: uuid := string([]byte(log[:36])). strings.Clone(log[:36]) is another supplied copying form. section 5.6 section 5.7

Choose the substring technique according to the data and its lifetime:

  • Slice directly when byte positions are intentional and retaining the original backing storage is acceptable. section 5.6
  • Convert to []rune before selecting a rune index or handling characters encoded with multiple bytes. section 5.6
  • Copy a small substring when the source is large and the result will outlive the source operation. section 5.7

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains byte-versus-rune slicing and shared backing arrays, then demonstrates copying; it does not specify compiler-independent sharing behavior.
Examples
Uses Hello, World!, multibyte Hêllo, and UUID-prefixed log messages to expose byte indexing and retention effects.
What it assumes
Assumes basic Go strings and teaches the distinction between bytes, runes, and shared string storage.
What you can do after
Diagnose substring-related retention and choose byte slicing, rune conversion, or copying for the situation.
How it connects
Connects substrings with strings, runes, []rune, []byte, string copying, and memory leaks.

Also explained in

Compare how 5 books explain substring →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.