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


现在这样是对的。使用 switch 在逻辑上是无效的。只有当字母数量等于该字母的 ASCII 码时,对应的 case 才会被执行。

感谢,找到了另一种方法

func main() {
    fmt.Println("hello world")
}

string.Count() 返回一个整数,表示在源字符串中找到子字符串的次数。因此: numOfa := strings.Count(string(s), "a") 返回 1

我认为使用映射会更简单。例如:

package main

import (
	"fmt"
	"strings"
)

type vowelMap map[string]int
type MyString string

// 为 MyString 类型创建查找元音的方法
func (m MyString) findAndCountVowel() vowelMap {
	vm := make(vowelMap)
	vowels := "aeiou"

	for _, vowel := range m {
		if strings.ContainsRune(vowels, vowel) {
			ch := string(vowel)
			vm[ch] = vm[ch] + 1
		}
	}
	return vm
}

func main() {
	var s MyString = "Hey! Lets see how many vowels we got "

	// 获取字符串中的元音
	m := s.findAndCountVowel()
	fmt.Printf("Vowels are %v", m)
}

在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语句的误用

可以提供具体的代码片段来进一步诊断问题。

回到顶部