Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 978
S_Nissan Avatar asked Oct 22 '25 19:10

S_Nissan


2 Answers

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.

like image 125
topskip Avatar answered Oct 24 '25 14:10

topskip


Why do you need a switch for this boolean output?

Use the following inbuilt function.

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

like image 44
Pratheesh M Avatar answered Oct 24 '25 13:10

Pratheesh M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!