Golang中switch语句的简单问题求助

Golang中switch语句的简单问题求助 我的问题是,为什么这段代码可以工作:

switch {
    case cfg.PlayNew.TreeReportingOptions.Type == "very narrow":
        treeMoveWidth = 1
    case cfg.PlayNew.TreeReportingOptions.Type == "narrow":
        treeMoveWidth = 3
    case cfg.PlayNew.TreeReportingOptions.Type == "regular":
        treeMoveWidth = 8

    }

但是这段却不行???注意:cfg.PlayNew.TreeReportingOptions.Type 是一个字符串

switch cfg.PlayNew.TreeReportingOptions.Type {
    case "very narrow":
        treeMoveWidth = 1
    case "narrow":
        treeMoveWidth = 3
    case "regular":
        treeMoveWidth = 8

    }

感谢您抽出时间!


更多关于Golang中switch语句的简单问题求助的实战教程也可以访问 https://www.itying.com/category-94-b0.html

3 回复

原来代码里有一个不可打印字符,所以它才无法编译。

更多关于Golang中switch语句的简单问题求助的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


第二个示例应该能正常工作。这段代码:

func main() {
	treeMoveWidth := 0
	treeReportingOptionsType := "narrow"
	switch treeReportingOptionsType {
	case "very narrow":
		treeMoveWidth = 1
	case "narrow":
		treeMoveWidth = 3
	case "regular":
		treeMoveWidth = 8
	}
	fmt.Println("treeMoveWidth =", treeMoveWidth)
}

… 会打印出以下结果:

treeMoveWidth = 3

你可以在 Go Playground 上亲自运行它。

在Go语言中,这两种switch语句的用法都是正确的,但它们的语法形式不同。您提供的第二段代码在语法上完全有效,如果无法工作,可能是由于其他原因。

让我解释一下这两种形式的区别:

第一种形式:无表达式switch

switch {
    case cfg.PlayNew.TreeReportingOptions.Type == "very narrow":
        treeMoveWidth = 1
    case cfg.PlayNew.TreeReportingOptions.Type == "narrow":
        treeMoveWidth = 3
    case cfg.PlayNew.TreeReportingOptions.Type == "regular":
        treeMoveWidth = 8
}

这种形式中,每个case后面都是一个布尔表达式,switch会按顺序评估每个case,直到找到第一个为true的表达式。

第二种形式:带表达式的switch

switch cfg.PlayNew.TreeReportingOptions.Type {
    case "very narrow":
        treeMoveWidth = 1
    case "narrow":
        treeMoveWidth = 3
    case "regular":
        treeMoveWidth = 8
}

这种形式中,switch表达式的结果会与每个case的值进行比较。

两种形式都有效的完整示例:

package main

import "fmt"

type Config struct {
    PlayNew struct {
        TreeReportingOptions struct {
            Type string
        }
    }
}

func main() {
    cfg := Config{}
    cfg.PlayNew.TreeReportingOptions.Type = "narrow"
    
    var treeMoveWidth int
    
    // 第一种形式
    switch {
    case cfg.PlayNew.TreeReportingOptions.Type == "very narrow":
        treeMoveWidth = 1
    case cfg.PlayNew.TreeReportingOptions.Type == "narrow":
        treeMoveWidth = 3
    case cfg.PlayNew.TreeReportingOptions.Type == "regular":
        treeMoveWidth = 8
    }
    fmt.Printf("方法1结果: %d\n", treeMoveWidth)
    
    // 第二种形式
    switch cfg.PlayNew.TreeReportingOptions.Type {
    case "very narrow":
        treeMoveWidth = 1
    case "narrow":
        treeMoveWidth = 3
    case "regular":
        treeMoveWidth = 8
    }
    fmt.Printf("方法2结果: %d\n", treeMoveWidth)
}

如果您的第二段代码无法工作,请检查:

  1. 字符串值是否有额外的空格或大小写问题
  2. 确保cfg.PlayNew.TreeReportingOptions.Type已正确初始化
  3. 检查是否有编译错误或运行时panic

两种语法都是正确的Go代码,第二段代码应该可以正常工作。

回到顶部