Go: Type assertions and type switches
A type assertion provides access to an interface's concrete value.
The type assertion x.(T)
asserts that the concrete value stored in x
is of type T
, and that x
is not nil. More precisely:
- If
T
is not an interface, it asserts that the dynamic type ofx
is identical toT
. - If
T
is an interface, it asserts that the dynamic type ofx
implementsT
.
var x interface{} = "foo"
var s string = x.(string)
fmt.Println(s) // "foo"
s, ok := x.(string)
fmt.Println(s, ok) // "foo true"
n, ok := x.(int)
fmt.Println(n, ok) // "0 false"
n = x.(int) // ILLEGAL
panic: interface conversion: interface {} is string, not int
A type switch performs several type assertions in series and runs the first case with a matching type:
var x interface{} = "foo"
switch v := x.(type) {
case nil:
fmt.Println("x is nil") // here v has type interface{}
case int:
fmt.Println("x is", v) // here v has type int
case bool, string:
fmt.Println("x is bool or string") // here v has type interface{}
default:
fmt.Println("type unknown") // here v has type interface{}
}
x is bool or string
Comments
Be the first to comment!