목차
switch 조건문
단일 케이스 switch 구문
default 키워드
복수 케이스 switch 구문
switch 조건문
여러 각각의 경우에 실행할 코드를 정의 가능.
C, C# , C++ , Java , JavaScript , PHP 언어의 switch 구문과 유사.
차이점은 일치하는 경우만 실행하므로 break문 불필요 .
단일 케이스 switch 구문
switch expression {
case x :
// x일 때 실행할 코드
case y :
// y일 때 실행할 코드
case z :
...
default:
// x~z 아닐 때 기본 실행할 코드
}
PS1. default 키워드는 선택 사항.
PS2. expression 과 각 case의 값(x, y,...,z)은 동일 자료형이야 함.
PS3. case의 값(x, y,...,z)은 소괄호 ()로 감싸도 됨.
[예제]
package main
import ("fmt")
func main() {
day := 4
switch day {
case 1:
fmt.Println("월")
case 2:
fmt.Println("화")
case 3:
fmt.Println("수")
case 4:
fmt.Println("목")
case 5:
fmt.Println("금")
case 6:
fmt.Println("토")
case 7:
fmt.Println("일")
}
}
결과값: 목
default 키워드
어떤 경우에도 해당하지 않을 때 기본으로 실행할 코드 지정.
[예제1]
package main
import ("fmt")
func main() {
day := 8
switch day {
case 1:
fmt.Println("월")
case 2:
fmt.Println("화")
case 3:
fmt.Println("수")
case 4:
fmt.Println("목")
case 5:
fmt.Println("금")
case 6:
fmt.Println("토")
case 7:
fmt.Println("일")
default:
fmt.Println("요일 코드 오류")
}
}
결과값: 요일 코드 오류
[예제2] - expression과 case의 값 자료형이 다르면 에러 발생.
package main
import ("fmt")
func main() {
a := 3
switch a {
case 1:
fmt.Println("a == 1")
case "b" :
fmt.Println("a == b")
}
}
결과값:
# command-line-arguments
.\homzzang.go:13:2: cannot use "b" (type untyped string) as type int
[예제3] - case의 값은 소괄호 ()로 감싸도 됨.
package main
import ("fmt")
func main() {
var day = 2
switch day {
case (1) :
fmt.Print("일")
case (2) :
fmt.Print("토")
}
}
결과값: 토
복수 케이스 switch 구문
각 case에 대해서 여러 값 가능.
[구문]
switch expression {
case x,y:
// x 또는 y일 때 실행할 코드
case v,w:
// v 또는 w일 대 실행할 코드
case z:
...
default:
// 어떤 경우에도 해당 안 될 대 실행할 코드
}
[예제]
package main
import ("fmt")
func main() {
day := 5
switch day {
case 1,3,5:
fmt.Println("월수금")
case 2,4:
fmt.Println("화목")
case 6,7:
fmt.Println("주말")
default:
fmt.Println("날짜 코드 오류")
}
}
주소 복사
랜덤 이동
최신댓글