Fundamentos de Go
Go Variables and Constants: var, := and const
Two ways to declare a variable, what a zero value is, and values that never change.
O que você vai aprender
- var and :=
- Zero values
- const
Declaration → result
var year int0, the zero valuescore := 10int, inferredconst MaxScore = 100cannot changeDeclare, then use
Go has two ways to create a variable. var names the type, and := lets Go work out the type from the value. A variable that is declared without a value gets a zero value such as 0 or an empty string.
year is declared without a value, so it starts at 0 until 2009 is assigned. := can only be used inside a function and can declare several variables at once. A const cannot be changed after it is declared.
Pontos-chave
- var names the type; := infers it.
- A variable without a value starts at its zero value.
- A const cannot change.
Exemplo executável de Go
main.go
package main
import "fmt"
const MaxScore = 100
func main() {
var language string = "Go"
var year int // zero value: 0
score := 10 // short declaration, type inferred
score += 5
year = 2009
name, version := "gopher", 1.21
fmt.Println(language, year, score, MaxScore)
fmt.Println(name, version)
}
Go 2009 15 100
gopher 1.21Pratique
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.
Seu progresso está salvo neste navegador Entre para mantê-lo em todos os dispositivos.
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.
- Swap First and Last Exchange the first and last items of a list. Fácil
- Soma Acumulada Substitua cada valor pelo total acumulado até o momento. Fácil