if文
- よくあるelse if やelseが使える
- 初期化ステートメントが使用できる。(省略化)
- if文の最初に実行される
- この時に宣言された変数はif文の中でしか使えない
if 初期化ステートメント; 条件式{
} else if 条件式{
} else {
}
例
package main
import "fmt"
func main(){
if num := 10; num % 2 == 0{
fmtPrintln("2で割り切れる")
} else if num % 3 == 0{
fmt.Println("3で割り切れる")
} else{
fmt.Println("2でも3でも割り切れない")
}
}
switch文
- 上から下に評価していき、条件が合致した時点で
- if文と同様に初期化ステートメントが使用できる
例
package main
import "fmt"
func main(){
switch os := "aa"; os{
case "mac"
fmtPrintln("Macだよ")
case "windows"
fmtPrintln("Windowsだよ")
default
fmtPrintln("MacでもWindowsでもないよ")
}
}
条件式のないswitch
- if文の代わりのような感じで書ける
- if elseが長く続く様であればこちらを採用するなど
package main
import "fmt"
func main(){
time = 20
switch {
case t.Hour() < 12:
fmt.Println("朝だよ")
case t.Hour() < 17:
fmt.Println("昼だよ")
default:
fmt.Println("夜だよ")
}
}