if 와 switch

slee2·2021년 9월 8일
0

go language

목록 보기
4/6

if와 else

package main

import "fmt"

func main() {
	heistReady := false
	
  if heistReady {
		fmt.Println("Let's go!")
	} else {
    fmt.Println("Act normal.")
  }
}

if문은 일반 언어와 비슷하게 분기처리에 많이 쓰인다. 위 예시처럼 if 뒤에 ()괄호를 안붙여도 되고 붙여도 된다. 그리고 else를 쓰려면

if {
} else {
}

이렇게 중괄호 닫기뒤에 바로 붙혀 써야된다. 개행하고 새로 쓰면 오류가 뜬다.(이유는 모르겠다.) 그것말고는 다른 언어와 비슷하다.

if lockCombo == robAttempt {
    fmt.Println("The vault is now opened.")
  }

비교 연산자도 괄호를 안붙여도 된다.

if rightTime && rightPlace {
	fmt.Println("We're outta here!")
} else {
	fmt.Println("Be patient...")
}
if enoughRobbers || enoughBags {
	fmt.Println("Grab everything!")
} else {
	fmt.Println("Grab whatever you can!")
}

&& 나 || 기능도 같다. AND와 OR 기능이다.

다른 언어와 다른점

if문 안에서 for처럼 선언과 동시에 조건문을 사용할 수 있다.

if success := true; success {
	fmt.Println("We're rich!")
} else {
	fmt.Println("Where did we go wrong?")
}

switch

스위치문은 다른 언어와 다르게 break;를 사용하지 않아도 분기처리가 되는 것 같다.

clothingChoice := "sweater"
 
switch clothingChoice {
case "shirt":
  fmt.Println("We have shirts in S and M only.")
case "polos":
  fmt.Println("We have polos in M, L, and XL.")
case "sweater":
  fmt.Println("We have sweaters in S, M, L, and XL.")
case "jackets":
  fmt.Println("We have jackets in all sizes.")
default:
  fmt.Println("Sorry, we don't carry that")
}

다른 언어와 다른점

switch문도 if문과 마찬가지로 선언과 동시에 조건문을 만들 수 있다.

switch numOfThieves := 5; numOfThieves {
case 1:
	fmt.Println("I'll take all $", amountStolen)
case 2:
	fmt.Println("Everyone gets $", amountStolen/2)
case 3:
	fmt.Println("Everyone gets $", amountStolen/3)
case 4:
	fmt.Println("Everyone gets $", amountStolen/4)
case 5:
	fmt.Println("Everyone gets $", amountStolen/5)
default:
	fmt.Println("There's not enough to go around...")
}

0개의 댓글