본문 바로가기
Programming/Go

Go 학습하기 - 흐름 제어

by Daniel_ 2026. 10. 8.
package main

import "fmt"

func main() {
	var (
		healthyCnt   int
		warningCnt   int
		crashloopCnt int
	)
	const total = 10

	for i := 1; i <= total; i++ {
		restarts := (i * 3) % 7

		var status string
		switch {
		case restarts == 0:
			status = "Healthy"
			healthyCnt++
		case restarts < 3:
			status = "Warning"
			warningCnt++
		default:
			status = "CrashLoop"
			crashloopCnt++
		}
		fmt.Printf("pod-%d: restarts=%d %s\n", i, restarts, status)
	}
	fmt.Printf("Healthy=%d Warning=%d CrashLoop=%d\n", healthyCnt, warningCnt, crashloopCnt)

	if ratio := float64(healthyCnt+warningCnt) / float64(total); ratio >= 0.8 {
		fmt.Printf("cluster OK (%.1f%% healthy)\n", ratio*100)
	} else {
		fmt.Printf("cluster DEGRADED (%.1f%% healthy)\n", ratio*100)
	}

	for ready, step := 0, 0; ready < total; {
		ready += 3
		step++

		fmt.Printf("step %d: ready=%d\n", step, ready)
	}
}
// 실행결과
pod-1: restarts=3 CrashLoop
pod-2: restarts=6 CrashLoop
pod-3: restarts=2 Warning
pod-4: restarts=5 CrashLoop
pod-5: restarts=1 Warning
pod-6: restarts=4 CrashLoop
pod-7: restarts=0 Healthy
pod-8: restarts=3 CrashLoop
pod-9: restarts=6 CrashLoop
pod-10: restarts=2 Warning
Healthy=1 Warning=3 CrashLoop=6
cluster DEGRADED (40.0% healthy)
step 1: ready=3
step 2: ready=6
step 3: ready=9
step 4: ready=12

1. 반복문

for i := 1; i <= total; i++ {

}

i := 1; 로 for문에서 사용할 변수를 선언 및 초기화 할 수 있다. Go는 while문이 없음.

2. Switch문

switch {
	case restarts == 0:
		status = "Healthy"
		healthyCnt++
	case restarts < 3:
		status = "Warning"
		warningCnt++
	default:
		status = "CrashLoop"
		crashloopCnt++
}

break; 를 쓰지 않아도 case 하나가 끝나면 switch문을 빠져나간다. (위에서부터 조건에 해당하는 것 하나만 실행)

3. If 문

if ratio := float64(healthyCnt+warningCnt) / float64(total); ratio >= 0.8 {
	fmt.Printf("cluster OK (%.1f%% healthy)\n", ratio*100)
} else {
	fmt.Printf("cluster DEGRADED (%.1f%% healthy)\n", ratio*100)
}

if 문에서 사용할 변수를 선언 및 초기화 할 수 있다. else는 if의 닫는 중괄호 바로 옆에서 이어 쓴다. 밑으로 내리면 에러가 난다.
Printf함수에서 %를 사용하려면 %%로 쓴다.

'Programming > Go' 카테고리의 다른 글

Go 학습하기 - 변수  (0) 2026.10.07
Go 학습하기 - 문자열 출력  (0) 2026.10.07
Go 학습하기 - 설치  (0) 2026.10.06