Go Optimizations 101, Go Details & Tips 101 and Go Generics 101 are all updated for Go 1.25 now. The most cost-effective way to get them is through this book bundle in the Leanpub book store.

loop 3

What does the following program print?

package main

type Book struct {
	Pages int
}

func f() int {
	var books = []Book{{555}}
	for _, book := range books {
		book.Pages = 999
	}
	return books[0].Pages
}

func g() int {
	var books = []*Book{{555}}
	for _, book := range books {
		book.Pages = 999
	}
	return books[0].Pages
}

func main() {
	println(f(), g())
}

Choices:

Answer: 555 999

Run it on Go play.

Key points:
  • In a loop, each container element is copied to the second iteration variable, modifying the iteration variable doesn't change the values of container elements.
  • A struct value owns its fields. When a struct value is copied, all of its fields are also copied.
  • A pointer to a struct value doesn't own the fields of the struct value. It just references the struct value, a.k.a. it just references the fields of the struct value. When a pointer is copied, the values referenced by the pointer are not copied. After copying, the copy of the pointer references the same values as the original pointer.


(more articles ↡)

The Go 101 project is hosted on Github. Welcome to improve Go 101 articles by submitting corrections for all kinds of mistakes, such as typos, grammar errors, wording inaccuracies, description flaws, code bugs and broken links.

If you would like to learn some Go details and facts every serveral days, please follow Go 101's official Twitter account @zigo_101.

Tapir, the author of Go 101, has been on writing the Go 101 series books and maintaining the go101.org website since 2016 July. New contents will be continually added to the book and the website from time to time. Tapir is also an indie game developer. You can also support Go 101 by playing Tapir's games (made for both Android and iPhone/iPad):
Individual donations via PayPal are also welcome.

Articles in this book:

(more are coming ...)