liveBook · Manning

Side effect

As explained in 100 Go Mistakes and How to Avoid Them

A side effect is an observable change or interaction caused by evaluating or executing code beyond producing its direct return value.

A side effect is an observable change or interaction caused by evaluating or executing code beyond producing its direct return value. In Go, slicing can expose this mistake: a slice carries length and capacity while sharing a backing array with other slices. section 3.9

Appending through a subslice changes the original

Given s1 := []int{1, 2, 3}, s2 := s1[1:2], and s3 := append(s2, 10), s2 has spare capacity. append writes 10 into the shared backing array, producing s1=[1 2 10], s2=[2], and s3=[2 10]. The apparent update to s3 therefore changes s1 without assigning to s1 directly. section 3.9

The same hazard appears across function boundaries. Passing s[:2] limits the visible length, not necessarily the capacity; a function that appends can overwrite the third element of the caller’s slice. section 3.9

Choose a protection strategy according to the ownership and readability requirements:

  • Pass a copy when the function must not affect the original backing array; reconstruct the result afterward. This is safer but adds code and can reduce readability. section 3.9
  • Pass a full slice expression such as s[:2:2] when the function should see only two elements and any append should allocate separately. section 3.9
  • Treat package initialization as another deliberate side-effect mechanism: importing a package with _ runs its init functions even without a direct public-function dependency. section 2.3.1

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Traces backing-array updates, function boundaries, defensive fixes, and init ordering, but does not develop a general effect system.
Examples
Uses shared slices, function calls, defensive copies, full slice expressions, and blank-imported packages.
What it assumes
Assumes familiarity with Go slices, functions, packages, and basic initialization behavior.
What you can do after
Diagnose unexpected slice mutation and choose copying or capacity restriction to contain it.
How it connects
Connects slices, append, backing arrays, functions, capacity, packages, blank imports, and init functions.

Also explained in

Compare how 24 books explain side effect →

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.