switch문은 표현식을 평가하고 값과 일치하는 첫 번째 case를 실행해요.
긴 if ... else if 체인보다 더 깔끔한 대안인 경우가 많아요.
operatingSystem := "windows"
switch operatingSystem {
case "windows":
// do something if the operating system is windows
case "linux":
// do something if the operating system is linux
case "macos":
// do something if the operating system is macos
default:
// do something if the operating system is none of the above
}
여러 값을 쉼표로 하나의 case에 묶을 수 있어요.
표현식이 그중 하나와 같으면 해당 case가 일치해요:
switch operatingSystem {
case "windows", "linux":
// do something if the operating system is windows or linux
case "macos":
// do something if the operating system is macos
default:
// do something if the operating system is none of the above
}
switch 뒤의 표현식은 아예 생략할 수도 있어요.
그러면 각 case에 불리언 표현식이 들어가고, true로 평가되는 첫 번째 case가 실행돼요.
age := 21
switch {
case age > 20 && age < 30:
// do something if age is between 20 and 30
case age == 10:
// do something if age is equal to 10
default:
// do something else for every other case
}
if와 마찬가지로 switch는 표현식 앞에 짧은 초기화 문을 포함할 수 있어요.
그곳에서 선언한 변수는 switch 블록 스코프를 가져요:
switch v := getValue(); {
case v < 0:
// do something if v is less than 0
case v == 0:
// do something if v is 0
default:
// do something else for every other case
}
// v will not be accessible here
fallthrough는 다음 case의 본문을 표현식의 일치 여부와 상관없이 실행해요.
case 본문의 마지막 문이어야 하고, 실행할 다음 case가 있어야 해요.
fallthrough는 관용적인 Go 코드에서는 흔하지 않은데, 인접한 case끼리 서로 의존하게 만들기 때문이에요.
그 결과 각 case를 따로 떼어 생각하기 어려워지고, switch를 읽기 더 어렵게 만들어요.
여러 case가 같은 동작을 해야 할 때는 쉼표로 묶는 게 더 명확해요.
다른 이유로 여러 case에서 로직을 공유해야 할 때는 공통 로직을 헬퍼 함수로 추출하는 것을 고려해 봐요.
s := "hello"
switch s {
case "hello":
fmt.Println("hello")
fallthrough
case "world":
fmt.Println("world") // also runs, even though s != "world"
}
// Output:
// hello
// world
더 알아보려면 Go by Example: Switch나 Go 언어 명세를 확인해 봐요.