liveBook · Manning

Backing array

As explained in Go by Example

A backing array is the array that stores the elements referenced by a Go slice.

A backing array is the array that stores the elements referenced by a Go slice. Different slices can reference the same backing array, so changing an element through one slice can change what another slice observes. section 5.4.3

Variadic arguments can share storage

A variadic function such as testRun(args ...string) receives a local slice. Calling testRun("-c=2", "-n=1", "https://github.com/inancgumus") gives that local slice a new backing array. Calling testRun(args...) shares the input slice’s backing array. If testRun assigns args[0] = "MODIFIED", the original slice changes. Passing testRun(append([]string{}, args...)...) copies the elements into a slice with a new backing array, keeping the original unchanged. section 5.4.3

Listing 5.6 Test runner helper (hit/cmd/hit_test.go)
func testRun(args ...string) (*testEnv, error) {  #1
    var tenv testEnv  #2
    err := run(&env{  #3
        args:   append([]string{"hit"}, args...),  #4
        stdout: &tenv.stdout,  #5
        stderr: &tenv.stderr,   #5
        dryRun: true,  #6
    })
    return &tenv, err  #7
}

Inspect the test runner helper to see append create the command-argument slice while the variadic parameter receives its elements. section 5.4.3

Backing arrays also affect memory use. io.ReadAll initially reads into a newly allocated 512-byte block, then repeatedly uses append; depending on the response size, this can allocate new backing arrays multiple times. Reading an entire response therefore stores all bytes and may increase garbage-collector and CPU pressure. section 7.3.3

How Go by Example covers it

How deep it goes
Explains shared storage, copying, append-driven reallocation, and memory pressure without detailing slice internals beyond backing arrays.
Examples
Uses a test runner’s argument slice and an HTTP response body consumed with io.ReadAll.
What you can do after
Diagnose unintended slice mutations and recognize when append-based reading may create repeated allocations.
How it connects
Connects Go slices, variadic functions, append, io.Reader, io.ReadAll, and garbage collection.

Also explained in

Compare how 3 books explain backing array →

Related concepts

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