Structs e interfaces

Go Pointers: & and *

Share a value instead of copying it, so a function can change the original.

  • Intermediário
  • 4 min de leitura
  • 1 exemplo executável
O que você vai aprender
  • & 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.

Pontos-chave

  1. Go copies arguments by default.
  2. &number is the address of number.
  3. *pointer reads or changes the value there.

Exemplo executável de Go

Go
Executar código →
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)
}
Gerar um botão Run para este exemplo Resultado da execução
21
42
7 7 true
1
true

Pratique

Abra o exemplo no compilador online, mude um valor ou adicione uma linha e tente prever a saída antes de executar. Depois quebre o código de propósito e leia a mensagem do compilador.

Terminou esta lição?

Marque como aprendida para acompanhar seu progresso.

Próxima: Interfaces →

Pratique com um desafio

Use o conteúdo desta lição para resolver um problema real. Cada desafio roda no navegador, com testes instantâneos e uma revisão por IA.

Todos os desafios