더북(TheBook)

switch 문으로 타입 변환

인터페이스 변수를 실제 타입으로 변환할 때 변환할 타입을 확실히 알고 있다면 타입 어설션으로 변환하면 된다. 하지만 실제 타입이 무엇인지 확실하지 않을 때는 switch 문으로 타입을 확인하는 것이 좋다.

다음 checkType() 함수에서는 switch 문으로 타입을 먼저 확인한 후 실제 값과 타입을 출력한다.


func checkType(v interface{}) {
    switch v.(type) {
    case bool:
        fmt.Printf("%t is a bool\n", v)
    case int, int8, int16, int32, int64:
        fmt.Printf("%d is an int\n", v)
    case uint, uint8, uint16, uint32, uint64:
        fmt.Printf("%d is an unsigned int\n", v)
    case float64:
        fmt.Printf("%f is a float64\n", v)
    case complex64, complex128:
        fmt.Printf("%f is a complex\n", v)
    case string:
        fmt.Printf("%s is a string\n", v)
    case nil:
        fmt.Printf("%v is nil\n", v)
    default:
        fmt.Printf("%v is unknown type\n", v)
    }
}

실행 결과

checkType(3)             // 3 is an int
checkType(1.5)           // 1.500000 is a float64
checkType(complex(1, 5)) // (1.000000+5.000000i) is a complex
checkType(true)          // true is a bool
checkType("s")           // s is a string
checkType(struct{}{})    // {} is unknown type
checkType(nil)           // <nil> is nil
신간 소식 구독하기
뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.