I have a []interface{}
I am iterating over, and checking the type of each element within a switch. I would like to add a 'catch-all' case for any of several numeric types, i.e. int || float32 || float64
.
It seems we are able to check whether an element is of a single distinct type, but I have not been able to figure out the syntax for checking multiple types with ||
(or).
Is this possible? What I've tried (Playground):
package main
import (
"fmt"
)
func main() {
things := []interface{}{"foo", 12, 4.5, true}
for _, thing := range things {
switch t := thing.(type) {
// How can we implement logical OR for types to implement a catch-all for numerics?
// Throws error: "type <type> is not an expression"
// case ( int || float64 ) :
// fmt.Printf("Thing %v is a 'numeric' type: %T
", thing, t)
// Single discrete types work fine, of course
case string :
fmt.Printf("Thing %v is of type: %T
", thing, t)
case int :
fmt.Printf("Thing %v is of type: %T
", thing, t)
case float64 :
fmt.Printf("Thing %v is of type: %T
", thing, t)
case bool :
fmt.Printf("Thing %v is of type: %T
", thing, t)
default :
fmt.Printf("Thing %v is of unknown type
", thing)
}
}
}
Well, I thought you couldn't, until I read the spec. You can, and it works just like multiple cases in any other switch
in Go:
case bool, string:
printString("type is bool or string") // type of i is type of x (interface{})
Yes, it's possible. But then t
has the type of interface{}
in any compound case
s or in the default
case.
switch t := v.(type) {
case string:
// t is of type string
case int, int64:
// t is of type interface{}, and contains either an int or int64
default:
// t is also of type interface{} here
}