Instead of asserting the type every time in a switch
statement, assign the
result of type assertion to a variable and use it.
A type assertion provides access to an interface's underlying concrete value.
The following statement asserts that the interface value i
holds the concrete type
T
assigns the underlying T
value to the variable t
. The statement will trigger
panic if i
does not hold a T
.
t := i.(T)
Hence, the recommendation of using the result of type assertion is idiomatic and straightforward. Also, it saves from the following bad practice:
switch x.(type) {
case int:
// Triggers a panic as "x" doesn't hold
// concrete type "string" but "int"
fmt.Println(x.(string))
}
switch x.(type) {
case int:
fmt.Println(x.(int))
}
switch x := x.(type) {
case int:
fmt.Println(x)
}