liveBook · Manning

Value copy

As explained in Go in Action, Second Edition

Copy by value is an assignment behavior in which a variable receives an independent copy of another value's data.

Value copy is Go’s default assignment behavior for most types, including numbers, strings, structs, and arrays. Assigning one variable to another creates an independent copy, so later changes to the original do not alter the copy. section 5.3

The distinction matters when iterating over arrays. A two-value range loop returns the index and a copy of the value at that index; changing the loop variable does not change the array. Use the index to modify the original element, or use an array of pointers when shared values are intended. section 4.1.4

Changing an array through the index

This loop changes only temporary copies: `for _, s := range strings { s = s + "!" }`, leaving `[hello gophers]`. Updating through the index changes the array: `for i := range strings { strings[i] = strings[i] + "!" }`, producing `[hello! gophers!]`. section 4.1.4

Copying versus sharing

With `var i = "foo"; var j = i`, changing `i` to `"bar"` leaves `j` as `"foo"`. With `var j = &i`, `j` stores i’s address, and dereferencing it with `*j` observes the updated value. section 5.3

strings := [...]string{"hello", "gophers"}
// Get each element of the array as variable 's'.
for _, s := range strings {
	// Add an exclamation point.
	s = s + "!"
}
fmt.Println(strings)
// output: [hello gophers]

Shows the common range-loop mistake where modifying the copied value leaves the source array unchanged. section 4.1.4

for i := range strings {
	strings[i] = strings[i] + "!"
}
fmt.Println(strings)
// output: [hello! gophers!]

Shows the index-based range-loop form that writes directly to the original array elements. section 4.1.4

How Go in Action, Second Edition covers it

How deep it goes
Defines assignment copying, demonstrates array mutation consequences, and contrasts copies with pointer-based shared memory.
Examples
Uses array range loops, string-array updates, string assignment, pointer dereferencing, and pointer-based struct construction.
What it assumes
Assumes basic Go variables and arrays while introducing pointer addresses, dereferencing, and independent assignment behavior.
What you can do after
Apply it via Go assignments and range loops while choosing indices or pointers when mutations must reach shared data.
How it connects
Connects value copy with range loops, arrays, pointers, structs, functions, and shared memory.

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.