capypad
0 day streak
go / beginner
Snippet

Type Assertions and Type Switches

Empty interface `interface{}` accepts any type. Type assertions extract the underlying type with `i.(type)` in switch or `i.(T)` for direct assertion. The comma-ok idiom checks if assertion succeeded before using the value.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package main
 
import "fmt"
 
func describe(i interface{}) {
switch v := i.(type) {
case nil:
fmt.Println("nil value")
case int:
fmt.Printf("int: %d\n", v)
case string:
fmt.Printf("string: %s\n", v)
case []int:
fmt.Printf("int slice with %d elements\n", len(v))
default:
fmt.Printf("unknown type: %T\n", v)
}
}
 
func main() {
describe(42)
describe("hello")
describe([]int{1, 2, 3})
var i interface{} = "test"
s := i.(string)
fmt.Println("Asserted string:", s)
if val, ok := i.(int); ok {
fmt.Println("Got int:", val)
} else {
fmt.Println("Not an int")
}
}
Breakdown
1
switch v := i.(type)
Type switch examines the dynamic type of interface
2
s := i.(string)
Direct type assertion, panics if wrong type
3
if val, ok := i.(int); ok
Comma-ok idiom safely checks assertion result
4
%T
Printf verb for printing the type of a value