Quidest?

Type switches in Go

ยท Lorenzo Drumond

A type switch is a construct that permits to do several type assertions in series.

A type switch is like a regular switch statement switch-expressions, but the cases in a type switch specify types (not values), and those values are compared against the type of the value held by the given interface value:

1switch v := i.(type) {
2case T:
3  // here v has type T
4case S:
5  // here v has type S
6default:
7  // no match; here v has the same type as i
8}

The declaration in a type switch has the same syntax as a type assertion i.(T) but the specific type T is replaced with the keyword type.

This switch statement tests whether the interface value i holds a value of type T or S. In each of the T and S cases, the variable v will be of type T or S respectively and hold the value held by i. In the default case (where there is no match), the variable v is of the same interface type and value as i.

E.g.:

 1package main
 2
 3import "fmt"
 4
 5func do(i interface{}) {
 6	switch v := i.(type) {
 7	case int:
 8		fmt.Printf("Twice %v is %v\n", v, v*2)
 9	case string:
10		fmt.Printf("%q is %v bytes long\n", v, len(v))
11	default:
12		fmt.Printf("I don't know about type %T!\n", v)
13	}
14}
15
16func main() {
17	do(21)
18	do("hello")
19	do(true)
20}
21
22// Output:
23// Twice 21 is 42
24// "hello" is 5 bytes long
25// I don't know about type bool!

References

#interface #golang #value #pass_by #programming #type #pointer #empty #switch #stack #methods #reference #panic #nil #for_the_love_of_go #values #heap #assertion