Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Go 为交换机内的类型实现逻辑或_Go_Types_Interface - Fatal编程技术网

Go 为交换机内的类型实现逻辑或

Go 为交换机内的类型实现逻辑或,go,types,interface,Go,Types,Interface,我有一个[]接口{}我正在迭代,并检查开关中每个元素的类型。我想为几种数字类型中的任何一种添加一个“全面覆盖”的情况,即int | | | float32 | | float64 似乎我们能够检查一个元素是否为单一的不同类型,但我还无法找出使用|(or)检查多个类型的语法 这可能吗?我所尝试的(): 主程序包 进口( “fmt” ) func main(){ 事物:=[]接口{}{“foo”,12,4.5,true} 对于u,thing:=范围事物{ 开关t:=事物(类型){ //我们如何实现逻

我有一个
[]接口{}
我正在迭代,并检查开关中每个元素的类型。我想为几种数字类型中的任何一种添加一个“全面覆盖”的情况,即
int | | | float32 | | float64

似乎我们能够检查一个元素是否为单一的不同类型,但我还无法找出使用
|
(or)检查多个类型的语法

这可能吗?我所尝试的():

主程序包
进口(
“fmt”
)
func main(){
事物:=[]接口{}{“foo”,12,4.5,true}
对于u,thing:=范围事物{
开关t:=事物(类型){
//我们如何实现逻辑OR for类型来实现数字的全面覆盖?
//抛出错误:“类型不是表达式”
//案例(int | | 64):
//fmt.Printf(“对象%v是‘数字’类型:%T\n”,对象,T)
//当然,单个离散类型可以很好地工作
大小写字符串:
fmt.Printf(“对象%v的类型为:%T\n”,对象,T)
案例int:
fmt.Printf(“对象%v的类型为:%T\n”,对象,T)
案例64:
fmt.Printf(“对象%v的类型为:%T\n”,对象,T)
案例布尔:
fmt.Printf(“对象%v的类型为:%T\n”,对象,T)
违约:
fmt.Printf(“对象%v的类型未知,\n”,对象)
}
}
}

好吧,我以为你不能,直到我告诉你。您可以,它的工作原理与Go中任何其他
开关的多个情况一样:

case bool, string:
    printString("type is bool or string")  // type of i is type of x (interface{})

是的,有可能。但是
t
在任何复合
case
s或
default
case中都有
interface{}
的类型

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
}

哦,天哪,简单!这里有一个‘问题’——如果我们有:case int,int64,我们不能稍后在开关下检查case int。谢谢@Flimzy@gpanda这不是这种开关的问题,而是每个Go开关的问题。只要找到匹配项,它就不会检查下一个案例<代码>直通
转到
可用于避免此问题。你对这个感兴趣吗?我可以给你一个例子,但我需要更多的空间,而不是一个评论。如果您不需要它,就不会将其作为答案发布,因为它不会提供现有答案之外的任何其他内容。@adrio:我想您的意思是
故障排除
,但故障排除在类型开关上不起作用。
故障排除
是的,很抱歉输入错误。它在类型开关上不起作用吗?我不知道。我想我们每天都会学到新的东西。我想我也应该去操场看看我发现了什么。它与故障排除无关。类型开关的复合外壳可转换为合适的类型。嗯,他们至少会打印出来。非常有帮助,谢谢你@Adrian。我觉得自己很傻,因为我经常会看到像我这样的问题,比如“哎呀,去读文档吧”,但我在搜索与“类型”相关的文档,而不是想看看开关。感觉改进的一半是精明的博士搜寻能力:)我最喜欢的一件事是围棋非常简单,你可以在一两个小时内阅读规范。当然,保留所有细节完全是另一回事!
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
}