appendix E  Passing by value or by reference

We constantly use functions in our code, and, most of the time, they have parameters. Let’s imagine we’re writing code for the bowling alley that opened last week. We need to print the scores on the screen after a player’s turn. We write the function shown in the following listing.

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, so 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                        
}                                

After writing a simple test, we realize 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 known as passing parameters by value and passing parameters by reference.

E.1 Go passes everything by value

E.1.1 Copying parameters on the stack

E.1.2 Using pointers

E.1.3 Shallow copies

E.1.4 Functions vs. methods