2015-11-13 35 views
1

我是新來的,無法弄清楚爲什麼最後一個案例子句(連接和測試)落入默認值。但具有新行字符(退出\ r \ n和連接\ r \ n)的人不要開關盒語句落到默認

沒有貫穿性聲明。

我已經試過標記交換機,並呼籲破[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) 
} 
+0

在默認情況下處理連接後,您可能會收到什麼嗎?嘗試在交換機之前打印cmds [i],看看有沒有你不期待的東西。 –

+0

在開關語句如fmt.Printf(「>>>%s <<<」,cmds [i])之前,在迴路中使用print語句排除故障您可能會發現「exit」和「connect」沒有新行 – openwonk

回答

-1

嘗試包裝你的switch語句的主體與strings.Trim()像這樣:

switch strings.TrimSpace(cmds[i]) { 
    // your cases 
} 

一般來說,它看起來像內循環是在這種情況下使用的錯誤構造。在此基礎上段的代碼,你可能想要刪除,只是有cmds數組的第一個元素是你的switch語句的主題

1

The Go Programming Language Specification

Switch statements

「開關」語句提供多路執行。一個表達式或類型 說明符相比,「箱子」內部

表達切換

在表達開關,開關表達式求值和 情況下的表達式,它不必是常數,被評估 左從右到上和從上到下;第一個等於開關 表達式觸發執行關聯的 大小寫的語句;其他情況會被跳過。如果沒有大小寫匹配並且存在 「默認」情況,則執行其語句。最多隻能有一個 默認情況,它可能出現在「switch」語句的任何地方。 A 缺少的開關表達式等同於布爾值true。

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

最後switchcase條款("connect""test")不通過掉落到defaultcase條款。 switch聲明中的break聲明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"]

您的程序邏輯嚴重瑕疵。