golang 기초 - 조건문

한나리·2023년 6월 26일

Go

목록 보기
6/19
post-thumbnail

조건문 if

//짧은 구문의 if문
if 초기문; 조건문 {
	실행코드
}

//if문
if 조건문 {
	실행코드 
} 

//if - else 문
if 조건문 {
	실행코드 
} else {
	실행코드
}

//if - else if - else문
if 조건문 {
	실행코드 
} else if {
	실행코드
} else {
	실행코드
}
package main

import (
	"fmt"
)    
func main() {
	num :=0 //초기문 사용 안함
	if num ==1 {
		fmt.Println(num) 
  	} else if num ==2{
   		fmt.Println(num)
    } else if num ==3{
   		fmt.Println(num)
    } else if num ==4{
   		fmt.Println(num)
    } else if num ==5{
   		fmt.Println(num)
    } else {
    	fmt.Println("num is not 1, 2, 3, 4 or 5)" //실행
    }
    
	if num :=0; num ==1 { //초기문 사용, 조건문 블록 외부에서 사용 불가
		fmt.Println(num) 
  	} else if num ==2{
   		fmt.Println(num)
    } else if num ==3{
   		fmt.Println(num)
    } else if num ==4{
   		fmt.Println(num)
    } else if num ==5{
   		fmt.Println(num)
    } else {
    	fmt.Println("num is not 1, 2, 3, 4 or 5)" //실행
    }
    
}

조건문 switch

if문과 다르게 조건을 적지 않고, 변수로 적음
case 키워드로 조건을 적음

// switch문
switch 비교값 {
	case1 :
    	실행코드
    case2 :
    	실행코드
    default :
    	실행코드
}

switch os := runtime.GOOS; os {
	case "darwin":
    	fmt.Println("OS X.")
    case "linux":
    	fmt.Println("Linux.")
    default:
    	fmt.Println("%s. \n", os)
}        

package main

import (
	"fmt"
)    

 func main() {
	switch num:= 10; num {
    	case 1, 3, 5, 7, 9:
			fmt.Println("Odd") 
        case 2, 4, 6, 8, 10:
        	fmt.Println("Even") //실행
  		default:
        	fmt.Println("Unknown")
    } 
}

package main

import (
	"fmt"
    "runtime"
)    

 func main() {
	fmt.Println(runtime.GOOS) //darwin
    
    switch os := runtime.GOOS; os {
	case "darwin":
    	fmt.Println("Mac OS") //실행
    case "linux":
    	fmt.Println("Linux")
    case "windows":
    	fmt.Println("Windows")
    default:
    	fmt.Println("%s. \n", os)
	}        
}

%s : 스트링 출력

profile
내가 떠나기 전까지는 망하지 마라, 블록체인 개발자

0개의 댓글