doutuo3899
2012-07-17 21:39
浏览 68
已采纳

为什么在类型开关中不允许掉线?

I'm wondering why fallthrough isn't allowed in a type switch statement in golang.

According to the specification: "The "fallthrough" statement is not permitted in a type switch.", which doesn't explain much about WHY it isn't allowed.

The code attached is to simulate a possible scenario were a fallthrough in a type switch statement might have been useful.

Notice! This code doesn't work, it will produce the error: "cannot fallthrough in type switch". I'm just wondering what possible reasons might have been for not allowing the fallthrough statement in a type switch.

//A type switch question
package main

import "fmt"

//Why isn't fallthrough in type switch allowed?
func main() {
    //Empty interface
    var x interface{}

    x = //A int, float64, bool or string value

    switch i := x.(type) {
    case int:
        fmt.Println(i + 1)
    case float64:
        fmt.Println(i + 2.0)
    case bool:
        fallthrough
    case string:
        fmt.Printf("%v", i)
    default:
        fmt.Println("Unknown type. Sorry!")
    }
}

图片转代码服务由CSDN问答提供 功能建议

我想知道为什么在golang的类型切换语句中不允许掉线。</ p>

根据规范:“在类型切换中不允许使用“ fallthrough”语句。” </ p>

附带的代码是为了模拟可能发生的情况,因为如果类型转换语句中的错误可能有用,就不会解释它。</ p> \ n

注意!</ strong>。此代码不起作用,它将产生错误:“无法在类型切换中掉线”。 我只是想知道为什么不允许类型转换中使用fallthrough语句的可能原因是什么?</ p>

  //类型转换问题
package main 
 
import“  fmt“ 
 
 ///为什么不允许类型切换掉线?
func main(){
 //空接口
 var x接口{} 
 
x = //一个int,float64,bool 或字符串值
 
开关i:= x。(type){
 case int:
 fmt.Println(i + 1)
 case float64:
 fmt.Println(i + 2.0)
 case  bool:
失败
大小写字符串:
 fmt.Printf(“%v”,i)
默认值:
 fmt.Println(“未知类型。抱歉!”)
} 
} 
 <  / code> </ pre> 
 </ div>

1条回答 默认 最新

相关推荐 更多相似问题