Check whether a string slice contains a certain value in Go

前端 未结 3 1053
春和景丽
春和景丽 2021-02-03 23:21

What is the best way to check whether a certain value is in a string slice? I would use a Set in other languages, but Go doesn\'t have one.

My best try is this so far:

3条回答
  •  萌比男神i
    2021-02-03 23:58

    You can use a map, and have the value e.g. a bool

    m := map[string] bool {"a":true, "b":true, "x":true}
    if m["a"] { // will be false if "a" is not in the map
        //it was in the map
    }
    

    There's also the sort package, so you could sort and binary search your slices

提交回复
热议问题