go / beginner
Snippet
Type Switches and Assertions
Type assertions access the concrete type stored in an interface variable. The syntax v.(T) returns the value and a boolean indicating success. Type switches compare the actual type rather than value, using the special keyword type. They are the idiomatic way to handle interface{} values when you need to inspect their underlying type. Always use the ok form to safely handle failed assertions and avoid panics.
snippet.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
35
package mainimport "fmt"func printType(v interface{}) {switch val := v.(type) {case int:fmt.Printf("Integer: %d\n", val*2)case string:fmt.Printf("String: %s (length: %d)\n", val, len(val))case bool:fmt.Printf("Boolean: %t\n", val)case []int:fmt.Printf("Int slice with %d elements\n", len(val))default:fmt.Printf("Unknown type\n")}}func main() {// Type assertionvar i interface{} = "hello"s, ok := i.(string)fmt.Printf("Assertion success: %v, value: %s\n", ok, s)// Failed assertionvar j interface{} = 42str, ok := j.(string)fmt.Printf("String assertion success: %v, value: %s\n", ok, str)printType(100)printType("Go rocks")printType(true)printType([]int{1, 2, 3})}
Breakdown
1
s, ok := i.(string)
Safe type assertion - ok is false if type doesn't match, no panic
2
switch val := v.(type) { ... }
Type switch uses 'type' keyword, val is scoped to each case
3
case int: fmt.Printf("%d\n", val*2)
Inside int case, val is an int (not interface{}), can use it directly
4
val, ok := j.(string)
Fails safely because j holds int, ok becomes false