Go の基礎
Go if, else and switch
Choose what runs with if and switch, including Go's switch without a value.
学べること
- 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.
重要なポイント
- Conditions are checked from top to bottom.
- switch does not fall through to the next case.
- A case can list several values.
実行できる Go のサンプル
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
weekend練習
サンプルをオンラインコンパイラーで開き、値を変えたり行を追加したりして、実行する前に出力を予想してみましょう。次に、わざとコードを壊してコンパイラーのメッセージを読んでみてください。
このレッスンを終えましたか?
学習済みにすると進み具合を記録できます。
進み具合はこのブラウザーに保存されています ログインすると、どのデバイスでも引き継げます。
チャレンジで練習する
このレッスンの内容を使って実際の問題を解きましょう。各チャレンジはブラウザで動き、すぐにテストされ、AI のレビューも受けられます。
すべてのチャレンジ