- Switch가 if문과 같은 느낌으로 사용이 가능하다. 아래 코드는 go lang tour에서 가져온 예시이다.
- case문에 직접 수식을 넣어서 사용한다.
func main() {
fmt.Println("When's Saturday?")
today := time.Now().Weekday()
switch time.Saturday {
case today + 0:
fmt.Println("Today.")
case today + 1:
fmt.Println("Tomorrow.")
case today + 2:
fmt.Println("In two days.")
default:
fmt.Println("Too far away.")
}
}
- 아래 예시는 정말 처음 보는 케이스 인데 switch에 switch 조건 변수, 조건 값이 없는 경우이다.
- 이 두가지 케이스를 보면 정말 if, elseif, else와 비슷한 방식으로 switch문을 사용할 수 있음을 알 수 있다.
func main() {
t := time.Now()
switch {
case t.Hour() < 12:
fmt.Println("Good morning!")
case t.Hour() < 17:
fmt.Println("Good afternoon.")
default:
fmt.Println("Good evening.")
}
}