strings.Contains in switch-case GoLang

huangapple go评论111阅读模式
英文:

strings.Contains in switch-case GoLang

问题

在Go语言中,switch语句的case条件只能是常量表达式,不能使用函数调用。因此,你不能在switch语句的case条件中使用strings.Contains函数。

如果你需要在switch语句中进行字符串匹配和过滤,你可以考虑使用if语句来实现。以下是一个示例:

  1. func function(str string) {
  2. if str == "str1" {
  3. // ...
  4. } else if strings.Contains(str, "test") {
  5. // ...
  6. } else {
  7. // ...
  8. }
  9. }

在上述示例中,我们使用了if语句来进行字符串匹配和过滤。首先,我们检查字符串是否等于"str1",如果是,则执行相应的代码块。如果不是,则继续检查字符串是否包含"test",如果包含,则执行相应的代码块。如果都不满足,则执行else代码块。

希望这可以帮助到你!如果你有任何其他问题,请随时问我。

英文:

Is it possible to use strings.Contains in switch case?
something like:

  1. func function(str string){
  2. switch str {
  3. case "str1":
  4. ...
  5. case strings.Contains("test"):
  6. ...
  7. default:
  8. ...
  9. }
  10. }

Edit: its an example, thats not the real case I need it for. Im filtering many results and I want all results that contains X and I also have cases that I need to fully match.

答案1

得分: 7

你可以这样做:

  1. package main
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. func main() {
  7. str := "testString"
  8. switch {
  9. case strings.Contains(str, "test"):
  10. fmt.Println(true)
  11. default:
  12. fmt.Println(false)
  13. }
  14. }

https://go.dev/play/p/_2fMd-3kE-r

没有参数的switch相当于switch true

英文:

You can do this:

  1. package main
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. func main() {
  7. str := "testString"
  8. switch {
  9. case strings.Contains(str, "test"):
  10. fmt.Println(true)
  11. default:
  12. fmt.Println(false)
  13. }
  14. }

https://go.dev/play/p/_2fMd-3kE-r

switch without argument is like switch true.

答案2

得分: 0

为什么你需要一个开关来控制这个布尔输出?

使用以下内置函数。

func strings.Contains(s string, substr string) bool

英文:

Why do you need a switch for this boolean output?

Use the following inbuilt function.

func strings.Contains(s string, substr string) bool

huangapple
  • 本文由 发表于 2022年3月10日 20:00:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/71423808.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定