Fundamentos de Go
Go if, else and switch
Choose what runs with if and switch, including Go's switch without a value.
O que você vai aprender
- if, else if, else
- if with a short statement
- switch and default
score = 87
- 1
score >= 90false, skip - 2
score >= 70true - 3
"Good"this branch runs
The first true branch runs
An if statement runs a block only when its condition is true. switch compares one value with several cases, or, without a value, picks the first case that is true.
The conditions are checked from top to bottom and only the first true branch runs, so 87 prints Good. An if can declare a variable before its condition, as remainder shows. A case can list several values, and Go does not fall through to the next case.
Pontos-chave
- Conditions are checked from top to bottom.
- switch does not fall through to the next case.
- A case can list several values.
Exemplo executável de Go
main.go
package main
import "fmt"
func main() {
score := 87
if score >= 90 {
fmt.Println("Excellent")
} else if score >= 70 {
fmt.Println("Good")
} else {
fmt.Println("Keep practicing")
}
if remainder := score % 2; remainder == 0 {
fmt.Println("even")
} else {
fmt.Println("odd")
}
switch {
case score >= 90:
fmt.Println("Grade: A")
case score >= 80:
fmt.Println("Grade: B")
default:
fmt.Println("Grade: C")
}
switch day := "sat"; day {
case "sat", "sun":
fmt.Println("weekend")
default:
fmt.Println("weekday")
}
}
Good
odd
Grade: B
weekendPratique
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.
- Letter Grade Turn a test score into a letter grade. Fácil
- Ano Bissexto Verifique se um ano segue a regra dos anos bissextos do calendário gregoriano. Fácil