gpa*_*nda -1 types interface go
我有一个[]interface{}
迭代,并检查交换机中每个元素的类型.我想为几种数字类型添加一个'catch-all'的情况,即int || float32 || float64
.
我们似乎能够检查一个元素是否是一个单独的不同类型,但我无法弄清楚用||
(或)检查多个类型的语法.
这可能吗?我试过的(游乐场):
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\n", thing, t)
// Single discrete types work fine, of course
case string :
fmt.Printf("Thing %v is of type: %T\n", thing, t)
case int :
fmt.Printf("Thing %v is of type: %T\n", thing, t)
case float64 :
fmt.Printf("Thing %v is of type: %T\n", thing, t)
case bool :
fmt.Printf("Thing %v is of type: %T\n", thing, t)
default :
fmt.Printf("Thing %v is of unknown type\n", thing)
}
}
}
Run Code Online (Sandbox Code Playgroud)
嗯,我认为你不能,直到我阅读规范.你可以,它就像switch
Go 中的任何其他案例一样:
case bool, string:
printString("type is bool or string") // type of i is type of x (interface{})
Run Code Online (Sandbox Code Playgroud)
是的,这是可能的。但是 then在任何复合s 或case 中t
都有类型。interface{}
case
default
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
}
Run Code Online (Sandbox Code Playgroud)