GoLang: Slice contains and dedup


The Blog of Tom Webster

  2016-05-11 15:19:17 PDT

The GoLang Gopher was created by Renee French and is licensed under the Creative Commons 3.0 Attributions license. Check out this blog post for details.

Here's a simple GoLang demonstration showing how to see whether or not a slice contains a value, then how to deduplicate the items in that slice. You can easily run this on the Go Playground, check it out!

package main

import "fmt"

func contains(intSlice []int, searchInt int) bool {
    for _, value := range intSlice {
        if value == searchInt {
            return true
        }
    }
    return false
}

func dedup(intSlice []int) []int {
    var returnSlice []int
    for _, value := range intSlice {
        if !contains(returnSlice, value) {
            returnSlice = append(returnSlice, value)
        }
    }
    return returnSlice
}

func main() {
    numbers := []int{1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6}
    fmt.Println("Numbers:", numbers)
    fmt.Println("Numbers contain 5:", contains(numbers, 5))
    fmt.Println("Numbers contain 8:", contains(numbers, 8))
    fmt.Println("Deduped numbers:", dedup(numbers))
}