appendix-e
Appendix E. Passing by value or by reference
This appendix covers
- Understanding what “passing by value” means
- Understanding what “passing by reference” means
- Two special cases: maps and slices
- A few recommendations to help make a choice
We constantly use functions in our code. These functions, most of the time, have parameters. Let’s imagine we are writing code for the bowling alley that opened last week. We need to print the scores on the screen after a player has had their shots. We write this function :
Listing E.1 Showing a player’s score
type Player struct {
name string
score int
}
// ShowScore displays the player’s score
func ShowScore(p Player) {
fmt.Printf("Player %q has %d points!\n", p.name, p.score)
}
This does the job, we’re happy. However, we notice that the function updating the score doesn’t seem to work.
Listing E.2 Updating the player’s score
func AddPoints(p Player, points int) {
p.score += points
}
Indeed, after writing a simple test, we realise that the player’s score after calling AddPoints didn’t change! The main reason behind this lies with Go’s handling of parameters in functions. The main concept here is known as passing parameters by value and passing parameters by reference.