Home > Backend Development > Golang > How to Find Unique Items in a Go Slice or Array?

How to Find Unique Items in a Go Slice or Array?

Mary-Kate Olsen
Release: 2024-11-01 04:16:27
Original
1021 people have browsed it

How to Find Unique Items in a Go Slice or Array?

Finding Unique Items in a Slice or Array

In Go, maintaining unique items in a slice or array can be challenging for newcomers. This guide addresses the issue, offering both a manual comparison method and a set-based alternative.

Manual Comparison Method

The manual comparison method involves looping through the array and checking each element against every other element. If a duplicate is found, it is skipped. Here's an optimized example:

<code class="go">visited := []visit{
    visit{1, 100},
    visit{2, 2},
    visit{1, 100},
    visit{1, 1},
}
unique := map[visit]bool{}

for _, v := range visited {
    unique[v] = true
}

var uniqueVisits []visit
for v := range unique {
    uniqueVisits = append(uniqueVisits, v)
}

fmt.Println(uniqueVisits)</code>
Copy after login

Set-Based Alternative

Go provides the map data structure that can be used as a set. A map with keys of type visit and values of type bool can be a convenient way to maintain unique values. Here's an example:

<code class="go">visited := []visit{
    visit{1, 100},
    visit{2, 2},
    visit{1, 100},
    visit{1, 1},
}
unique := map[visit]bool{}

for _, v := range visited {
    if !unique[v] {
        unique[v] = true
    }
}

var uniqueVisits []visit
for v := range unique {
    uniqueVisits = append(uniqueVisits, v)
}

fmt.Println(uniqueVisits)</code>
Copy after login

Output

Both methods will output the same result:

[visit{1 100} visit{2 2} visit{1 1}]
Copy after login

Choose the method that best suits your specific implementation requirements. The manual comparison method provides fine-grained control over element comparisons, while the set-based method offers simplicity and efficiency.

The above is the detailed content of How to Find Unique Items in a Go Slice or Array?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template