Golang中switch语句的default分支为何永远不会被调用?

Golang中switch语句的default分支为何永远不会被调用? 我写了这段代码,但收到一个错误提示说这个fmt.Errorf行永远不会被使用。其他所有case分支似乎都能正确匹配,但当我给command传入一个不匹配的值时…难道不应该执行default分支吗?

		switch {
		case strings.EqualFold("WRITE", command):
			fmt.Println("WRITING!")
		case strings.EqualFold("READ", command):
			fmt.Println("READING!")
		case strings.EqualFold("START", command):
			fmt.Println("STARING!")
		case strings.EqualFold("DELETE", command):
			fmt.Println("DELETING!")
		case strings.EqualFold("COMMIT", command):
			fmt.Println("COMMITTING!")
		case strings.EqualFold("ABORT", command):
			fmt.Println("ABORTING!")
		case strings.EqualFold("QUIT", command):
			fmt.Println("QUITTING!")
		default:
			fmt.Errorf("NO MATCH")
		}

更多关于Golang中switch语句的default分支为何永远不会被调用?的实战教程也可以访问 https://www.itying.com/category-94-b0.html

2 回复

好的,我得到了答案。

fmt.Errorf 会返回一个值。原来如此。

func main() {
    err := fmt.Errorf("an error occurred")
    if err != nil {
        fmt.Println(err)
    }
}

更多关于Golang中switch语句的default分支为何永远不会被调用?的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在Go语言中,switch语句的default分支确实会在所有case条件都不匹配时执行。但在你的代码中,编译器提示fmt.Errorf行永远不会被使用,这是因为fmt.Errorf函数返回一个error类型的值,而你没有使用这个返回值。

fmt.Errorf不会像fmt.Println那样直接输出内容到标准输出。它创建一个错误值,通常需要被返回、赋值给变量或用于其他处理。在你的代码中,由于没有使用这个返回值,编译器认为这是一个无用的表达式,因此报告该行永远不会被使用。

要修复这个问题,你可以:

  1. 使用fmt.Println输出错误信息:
default:
    fmt.Println("NO MATCH")
  1. 或者使用fmt.Errorf创建错误并返回/处理它:
default:
    return fmt.Errorf("NO MATCH")
  1. 或者将错误赋值给变量:
default:
    err := fmt.Errorf("NO MATCH")
    fmt.Println(err)

以下是修正后的示例:

switch {
case strings.EqualFold("WRITE", command):
    fmt.Println("WRITING!")
case strings.EqualFold("READ", command):
    fmt.Println("READING!")
case strings.EqualFold("START", command):
    fmt.Println("STARING!")
case strings.EqualFold("DELETE", command):
    fmt.Println("DELETING!")
case strings.EqualFold("COMMIT", command):
    fmt.Println("COMMITTING!")
case strings.EqualFold("ABORT", command):
    fmt.Println("ABORTING!")
case strings.EqualFold("QUIT", command):
    fmt.Println("QUITTING!")
default:
    fmt.Println("NO MATCH")
}

这样,当command不匹配任何case时,default分支会正常执行并输出"NO MATCH"。

回到顶部