Check whether a string slice contains a certain value in Go

前端 未结 3 961
春和景丽
春和景丽 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条回答
  •  忘了有多久
    2021-02-03 23:58

    To replace sets you should use a map[string]struct{}. This is efficient and considered idiomatic, the "values" take absolutely no space.

    Initialize the set:

    set := make(map[string]struct{})
    

    Put an item :

    set["item"]=struct{}{}
    

    Check whether an item is present:

    _, isPresent := set["item"]
    

    Remove an item:

    delete(set, "item")
    

提交回复
热议问题