Golang中如何在switch语句中正确匹配case的问题
Golang中如何在switch语句中正确匹配case的问题 我正在尝试编写一个根据条件输出不同情况的switch语句。但只有默认情况能正常工作,我觉得这不太理想。 https://play.golang.org/p/YZ9xmVrn0Jk
另外,有没有办法改进这个countVowel方法?我觉得它应该可以写得更好看些
func main() {
fmt.Println("hello world")
}
5 回复
您可以使用映射类型 - Go映射实战
更多关于Golang中如何在switch语句中正确匹配case的问题的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
感谢,找到了另一种方法
func main() {
fmt.Println("hello world")
}
在Go语言的switch语句中,case匹配默认是精确匹配,但根据你的描述,问题可能出现在条件表达式或case值上。以下是几种常见情况的解决方案:
1. 基础switch语句示例
package main
import "fmt"
func main() {
value := 2
switch value {
case 1:
fmt.Println("Value is 1")
case 2:
fmt.Println("Value is 2")
case 3:
fmt.Println("Value is 3")
default:
fmt.Println("Default case")
}
}
2. 带条件的switch语句
func checkNumber(num int) {
switch {
case num < 0:
fmt.Println("Negative number")
case num == 0:
fmt.Println("Zero")
case num > 0 && num < 10:
fmt.Println("Single digit positive")
default:
fmt.Println("Other number")
}
}
3. 改进的countVowel方法
func countVowels(s string) int {
vowels := map[rune]bool{
'a': true, 'e': true, 'i': true, 'o': true, 'u': true,
'A': true, 'E': true, 'I': true, 'O': true, 'U': true,
}
count := 0
for _, char := range s {
if vowels[char] {
count++
}
}
return count
}
4. 使用switch处理字符串匹配
func processInput(input string) {
switch input {
case "start", "begin":
fmt.Println("Starting process...")
case "stop", "end":
fmt.Println("Stopping process...")
case "pause":
fmt.Println("Pausing process...")
default:
fmt.Println("Unknown command")
}
}
5. 类型switch示例
func checkType(x interface{}) {
switch v := x.(type) {
case int:
fmt.Printf("Integer: %d\n", v)
case string:
fmt.Printf("String: %s\n", v)
case bool:
fmt.Printf("Boolean: %t\n", v)
default:
fmt.Printf("Unknown type: %T\n", v)
}
}
6. 更简洁的countVowel版本
func countVowels(s string) int {
count := 0
for _, c := range s {
switch c {
case 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U':
count++
}
}
return count
}
如果只有默认情况工作,检查:
- case值是否与switch表达式类型匹配
- 是否使用了正确的比较操作符
- 是否存在fallthrough语句的误用
可以提供具体的代码片段来进一步诊断问题。


