gpt4 book ai didi

go - Switch case 语句落空为 default

转载 作者:IT王子 更新时间:2023-10-29 02:23:40 29 4
gpt4 key购买 nike

我是新手,无法弄清楚为什么最后一个 case 子句(连接和测试)会变成默认值。但是那些带有换行符的(exit\r\n and connect\r\n)不

没有 fallthrough 语句。

我已经尝试标记开关并调用 break [lbl] 但默认 block 仍然被执行

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)
}

最佳答案

The Go Programming Language Specification

Switch statements

"Switch" statements provide multi-way execution. An expression or type specifier is compared to the "cases" inside

Expression switches

In an expression switch, the switch expression is evaluated and the case expressions, which need not be constants, are evaluated left-to-right and top-to-bottom; the first one that equals the switch expression triggers execution of the statements of the associated case; the other cases are skipped. If no case matches and there is a "default" case, its statements are executed. There can be at most one default case and it may appear anywhere in the "switch" statement. A missing switch expression is equivalent to the boolean value true.

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

最后一个 switch case 子句(“connect”“test”)不会落入default case 子句。 switch 语句 case 子句中的 break 语句跳出 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

>>

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

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

关于go - Switch case 语句落空为 default,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33684386/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com