Outils pour utilisateurs

Outils du site


tech:go_lang_-_if_x_in_list

Go lang - if x in list

Source : https://stackoverflow.com/questions/15323767/does-go-have-if-x-in-construct-similar-to-python

Since Go 1.18 or newer, you can use slices.Contains.

func main() {
        liste1 := []string{"Meow", "Waf", "Moo"}
 
        if !slices.Contains(liste1, "Waff") {
                fmt.Println("Aucun chien trouvé")
        } else {
                fmt.Println("Un chien a été trouvé")
        }
}

Before Go 1.18 there was no built-in operator. You needed to iterate over the array. You had to write your own function to do it, like this:

func stringInSlice(a string, list []string) bool {
    for _, b := range list {
        if b == a {
            return true
        }
    }
    return false
}

FIXME

tech/go_lang_-_if_x_in_list.txt · Dernière modification : de Jean-Baptiste

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki