Go: Append if unique

后端 未结 4 1608
深忆病人
深忆病人 2021-01-30 06:28

Is there a way to check slices/maps for the presence of a value?

I would like to add a value to a slice only if it does not

4条回答
  •  心在旅途
    2021-01-30 06:58

    Your approach would take linear time for each insertion. A better way would be to use a map[int]struct{}. Alternatively, you could also use a map[int]bool or something similar, but the empty struct{} has the advantage that it doesn't occupy any additional space. Therefore map[int]struct{} is a popular choice for a set of integers.

    Example:

    set := make(map[int]struct{})
    set[1] = struct{}{}
    set[2] = struct{}{}
    set[1] = struct{}{}
    // ...
    
    for key := range(set) {
      fmt.Println(key)
    }
    // each value will be printed only once, in no particular order
    
    
    // you can use the ,ok idiom to check for existing keys
    if _, ok := set[1]; ok {
      fmt.Println("element found")
    } else {
      fmt.Println("element not found")
    }
    

提交回复
热议问题