Switch case语句将变为默认值

时间:2015-11-13 01:16:36

标签: go switch-statement default

我是新手,无法弄清楚为什么最后一个案例子句(连接和测试)会失败。但是那些带有新行字符(退出\ r \ n和连接\ r \ n)的人不会

没有通过声明。

我已经尝试标记交换机并调用break [lbl],但默认块仍然被执行

package main

import (
"fmt"
"strings"
"bufio"
"os"
)

func main() {

var cmd string
bio := bufio.NewReader(os.Stdin)
fmt.Println("Hello")

proceed := true

for proceed {

    fmt.Print(">> ")
    cmd, _ = bio.ReadString('\n')
    cmds := strings.Split(cmd, " ")

    for i := range cmds{
        switch cmds[i]{
            case "exit\r\n" :
                proceed = false
            case "connect\r\n":
                fmt.Println("The connect command requires more input")
            case "connect":
                if i + 2 >= len(cmds) {
                    fmt.Println("Connect command usage: connect host port")
                } else {
                    i++
                    constring := cmds[i]
                    i++
                    port := cmds[i]
                    con(constring, port)    
                }
                fmt.Println("dont print anything else, dont fall through to default. There should be no reason why the default caluse is executed???")
            case "test":
                fmt.Println("dont print anything else, dont fall through to default. There should be no reason why the default caluse is executed???")
            default:
                fmt.Println("Unrecognised command: " + cmds[i])
        } 

    }

}
}

func con (conStr, port string){
panic (conStr)
}

2 个答案:

答案 0 :(得分:1)

  

The Go Programming Language Specification

     

Switch statements

     

“Switch”语句提供多路执行。表达式或类型   将说明符与

中的“案例”进行比较      

表达式切换

     

在表达式开关中,评估开关表达式并且   案例表达式,不必是常量,进行评估   从左到右,从上到下;第一个等于开关的   表达式触发执行相关联的语句   案件;其他案例被跳过。如果没有案例匹配且有一个   “默认”情况下,其语句被执行。最多可以有一个   默认情况下,它可能出现在“switch”语句中的任何位置。一个   缺少开关表达式相当于布尔值true。

ExprSwitchStmt = "switch" [ SimpleStmt ";" ] [ Expression ] "{" { ExprCaseClause } "}" .
ExprCaseClause = ExprSwitchCase ":" StatementList .
ExprSwitchCase = "case" ExpressionList | "default" .

最后switch case条款("connect""test")不属于default case条款。 break语句switch子句中的case语句会突破switch语句;它不会突破周围的for条款。

您尚未向我们提供可重现的示例:How to create a Minimal, Complete, and Verifiable example.。例如,您没有向我们展示您的输入和输出。

这是一个按预期工作的示例。有一个原因是default子句被执行。

>> test 127.0.0.1 8080
dont print anything else, dont fall through to default. There should be no reason why the default caluse is executed???
Unrecognised command: 127.0.0.1
Unrecognised command: 8080

>> 

cmdsfmt.Printf("%q\n", cmds)的值为["test" "127.0.0.1" "8080\r\n"]

你的程序逻辑存在严重缺陷。

答案 1 :(得分:-1)

尝试使用data.table包装switch语句的主题,如下所示:

strings.Trim()

一般来说,看起来内部for循环是在这种情况下使用的错误构造。根据这段代码,您可能希望删除它,并将switch strings.TrimSpace(cmds[i]) { // your cases } 数组的第一个元素作为switch语句的主题

相关问题