golang
interface{}, type assertions and type switches
vincenthanna
2019. 5. 29. 14:11
interface{}는 어떤 값도 될 수 있는 타입이다. 그 특성을 이용해서 내장된 타입이든 사용자 정의 타입이든 인자로 받을 수 있는 함수를 작성할 수 있다.
interface{}은 비슷한 타입이 없기 때문에 type conversion을 적용할 수 없다. 대신 type assertion을 사용한다.
var object interface{} = "hello"
str := object.(string)
type assertion이 실패하면 panic이 발생한다. 성공/실패 여부를 확인할 수 있는 변수를 추가로 사용해서 panic을 피하고 type assertion이 성공했는지 확인할 수 있다.
str, ok := object.(string)
interface{} 가 어떤 타입이 될 수 있는지 모르면 switch 문과 ‘type’ 키워드를 함께 사용해서 처리할 수 있다.
switch v := object.(type) {
case string:
fmt.Println(v)
case int32, int64:
fmt.Println(v)
case Data:
fmt.Println(v)
default:
fmt.Println("unknown")
}
위 코드는 switch의 특수한 구문으로, 괄호 안에 특정 type명을 쓰는 대신 ‘type’을 넣으면 case 구문에서 각각의 type에 대해 대응할 수 있다. v에는 interface{}의 실제 값이 들어간다.