liveBook · Manning

Slicing

As explained in Go in Action, Second Edition

A slice expression is Go syntax that creates a slice view over an index range of an array or slice while sharing the underlying storage.

Slicing lets a function work with just the part of an array or slice it needs, without copying the elements. A slice expression creates a new slice header pointing into the same backing storage. Changes to shared elements are therefore visible through either slice. section 4.2.6 section 4.2

Use `a[low:high]` to select a range:

  • `low` is included and `high` is excluded. For `letters := []string{"A", "B", "C", "D"}`, `letters[1:3]` contains `B` and `C`. section 4.2.6
  • Omit `low` to start at zero, as in `letters[:2]`; omit `high` to continue through `len(letters)`, as in `letters[2:]`. Slicing an array likewise produces a slice backed by that array. section 4.2.6
  • Use `a[low:high:max]` when the new slice should have less capacity for expansion. This limits how far an append can use the existing backing storage; it does not make shared elements independent. section 4.2.6 section 4.2

Average a measurement window

If `avg` accepts a `[]float64`, pass `avg(measurements[:10])` to average only the first ten readings, even when the collection contains more. Check `len(measurements) >= 10` first when the number of readings is uncertain: asking for an unavailable index causes a runtime panic. section 4.2.6 section 4.2.8

The same pattern keeps command-line processing focused: `for _, filename := range os.Args[1:]` visits filenames while leaving out the program name. `range` handles the resulting slice without a manual index limit. section 2.9

How Go in Action, Second Edition covers it

How deep it goes
Explains two- and three-index expressions through backing storage, length, and capacity, with examples of each form.
Examples
Uses command-line filenames and a subset of sensor readings, alongside indexed slice and array examples.
What it assumes
Assumes basic indexing and function calls while defining slice-expression bounds and their defaults.
What you can do after
Apply it via Go slice expressions to pass selected data to functions and constrain a view’s capacity.
How it connects
Connects slice expressions to arrays, backing arrays, capacity, append, range loops, and bounds checking.

Also explained in

Compare how 16 books explain slicing →

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.