[Go/Golang] Go 언어 조건문 (switch)

2022. 6. 10. 20:0003. Resources/Go

728x90
반응형

이번에는 switch문이다.

https://gobyexample.com/switch

 

Go by Example: Switch

Switch statements express conditionals across many branches. package main import ( "fmt" "time" ) func main() { Here’s a basic switch. i := 2 fmt.Print("Write ", i, " as ") switch i { case 1: fmt.Println("one") case 2: fmt.Println("two") case 3: fmt.Prin

gobyexample.com

 

이번 예제의 코드는 아래와 같다.

package main

import (
	"fmt"
	"time"
)

func main() {

    i := 2
    fmt.Print("Write ", i, " as ")
    switch i {
    case 1:
        fmt.Println("one")
    case 2:
        fmt.Println("two")
    case 3:
        fmt.Println("three")
    }

    switch time.Now().Weekday() {
    case time.Saturday, time.Sunday:
        fmt.Println("It's the weekend")
    default:
        fmt.Println("It's a weekday")
    }

    t := time.Now()
    switch {
    case t.Hour() < 12:
        fmt.Println("It's before noon")
    default:
        fmt.Println("It's after noon")
    }

    whatAmI := func(i interface{}) {
        switch t := i.(type) {
        case bool:
            fmt.Println("I'm a bool")
        case int:
            fmt.Println("I'm an int")
        default:
            fmt.Printf("Don't know type %T\n", t)
        }
    }
    whatAmI(true)
    whatAmI(1)
    whatAmI("hey")
}

switch 조건문도 별 다를 건 없는데

    whatAmI := func(i interface{}) {
        switch t := i.(type) {
        case bool:
            fmt.Println("I'm a bool")
        case int:
            fmt.Println("I'm an int")
        default:
            fmt.Printf("Don't know type %T\n", t)
        }
    }
    whatAmI(true)
    whatAmI(1)
    whatAmI("hey")

함수 안에 interface{} 라는 부분을 처음 봐서 신기했다.

이게 typescript에서 쓰는 interface와 같은 역할을 하는 것 같다.

저 부분의 결과는 아래처럼 나온다.

I'm a bool
I'm an int
Don't know type string

 

interface란 무엇인지 이 블로그에 잘 정리되어있다.

 

interface나 타입에 대해서는 나중에 더 잘 나오겠지!

 

반응형