Structs and Interfaces
Go Pointers: & and *
Share a value instead of copying it, so a function can change the original.
What you'll learn
- & takes an address
- * follows a pointer
- nil pointers
Passing 21 to a function
double(number)
- gets a copy
- number stays 21
doubleInPlace(&number)
- gets the address
- number becomes 42
An address instead of a copy
Go copies values when it passes them to a function. A pointer holds the address of a value, so a function that receives a pointer can change the original.
double changes only its own copy, so number stays 21. &number gives the address, and *value reads or changes what is stored there. Go follows a pointer to a struct for you, so counter.Count works. A pointer that points to nothing is nil.
Key points
- Go copies arguments by default.
- &number is the address of number.
- *pointer reads or changes the value there.
Runnable Go example
main.go
package main
import "fmt"
func double(value int) {
value *= 2 // changes only the copy
}
func doubleInPlace(value *int) {
*value *= 2 // changes the original through the pointer
}
type Counter struct{ Count int }
func main() {
number := 21
double(number)
fmt.Println(number)
doubleInPlace(&number)
fmt.Println(number)
pointer := &number
*pointer = 7
fmt.Println(number, *pointer, pointer == &number)
counter := &Counter{}
counter.Count++ // Go follows the pointer for you
fmt.Println(counter.Count)
var missing *Counter
fmt.Println(missing == nil)
}
21
42
7 7 true
1
truePractice
Open the example in the online compiler, change a value or add a line, and predict the output before you run it. Then break the code on purpose and read the compiler's message.
Finished this lesson?
Mark it as learned to track your progress.
Your progress is saved in this browser Sign in to keep it on every device.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Swap First and Last Exchange the first and last items of a list. Easy
- Linked List Operations Simulate a linked list: add at either end, remove from the front or by value, and reverse it. Easy