Post

08. switch문

08. switch문

✅ 1. switch문 형태

1.1 한 번에 여러 값 비교

  • case문에 , 로 조건문을 넣는 경우 OR로 동작한다
1
2
3
4
5
6
7
8
	day := "thursday"

	switch day {
	case "saturday", "sunday":
		fmt.Println("쉬는 날~")
	default:
		fmt.Println("일하는 날~")
	}

1.2 조건문 비교

  • switch true를 통해 조건문처럼 사용 가능하다
  • true는 생략 가능하다
1
2
3
4
5
6
7
8
9
10
	temp := 18

	switch ~~true~~ {                 // true 생략 가능
	case temp < 10, temp > 30:
		fmt.Println("별로다")
	case temp >= 10 && temp < 20:
		fmt.Println("괜찮다")
	default:
		fmt.Println("좋다")
	}

1.3 switch 초기문

  • switch문 내에서 초기화된 변수는 switch문이 종료되면 사라진다
1
2
3
4
5
6
7
8
	switch age := getMyAge(); age {
	case 10:
		fmt.Println("Teenage")
	case 33:
		fmt.Println("Pair 3")
	default:
		fmt.Println("My age is ", age)
	}

✅ 2. break와 fallthrough 키워드

  • Go에서는 break문을 사용하지 않아도 case 하나를 실행한 후에는 switch문을 빠져나간다
  • 다음 case문까지 실행하고 싶다면 fallthrough문을 사용해야 한다
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
type ColorType int

const (
	Red ColorType = iota
	Blue
	Green
)

func checkColor(color ColorType) {
	switch color {
	case Red:
		fmt.Println("Red")
	case Blue:
		fmt.Printf("Blue\t")
		fallthrough
	case Green:
		fmt.Println("Green")
	}
}

func main() {
	checkColor(Red)  // Red
	checkColor(Blue) // Blue	Green
}
This post is licensed under CC BY 4.0 by the author.