
124
러닝 Go
4.5
공백
switch
문
switch
문을 사용하는 또 다른 강력한 방법이 있다.
for
문 선언에서 모든 부분을 빼는 것과
같이
switch
문도 비교가 되는 값을 명시하지 않아도 된다. 이것을
공백
blank
switch
라 부른
다. 일반적인
switch
는 값이 같은지에 대한 확인만 할 수 있다. 공백
switch
는 각
case
문에
불리언 결과를 내는 비교는 모두 가능하다. [예제
4
-
21
]을
Go
플레이그라운드
17
에서 실행해
보도록 하자.
예제
4-21
공백
switch
words := []string{“hi”, “salutations”, “hello”}
for _, word := range words {
switch wordLen := len(word); {
case wordLen < 5:
fmt.Println(word, “is a short word!”)
case wordLen > 10:
fmt.Println(word, “is a long word!”)
default:
fmt.Println(word, “is exactly the right length.”)
}
}
해당 프로그램을 실행하면, 다음과 같은 결과를 볼 수 있다.
hi is a short word!
salutations is a long word!
hello is exactly ...