'strings.Contains in switch-case GoLang [closed]
Is it possible to use strings.Contains in switch case? something like:
func function(str string){
switch str {
case "str1":
...
case strings.Contains("test"):
...
default:
...
}
}
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.
Solution 1:[1]
You can do this:
package main
import (
"fmt"
"strings"
)
func main() {
str := "testString"
switch {
case strings.Contains(str, "test"):
fmt.Println(true)
default:
fmt.Println(false)
}
}
https://go.dev/play/p/_2fMd-3kE-r
switch without argument is like switch true.
Solution 2:[2]
Why do you need a switch for this boolean output?
Use the following inbuilt function.
func strings.Contains(s string, substr string) bool
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | topskip |
| Solution 2 | Pratheesh M |
