Home > Backend Development > Golang > How to Efficiently Remove Duplicate Items from a Slice in Go?

How to Efficiently Remove Duplicate Items from a Slice in Go?

DDD
Release: 2024-10-29 08:29:02
Original
813 people have browsed it

How to Efficiently Remove Duplicate Items from a Slice in Go?

Deleting Duplicate Items from a Slice

In your situation, you're encountering an issue when deleting duplicate items from a slice because you're iterating through the slice and removing elements while you're iterating. This can lead to index errors and panics if a duplicate item is located at the end of the slice.

To address this issue, a more efficient approach is to copy unique elements to the beginning of the slice and then trim any excess elements afterward. Here's how you can do it:

<code class="go">i := 0
for _, v := range cfg.Bootstrap {
    if v.PeerID == peer.PeerID && v.Address == peer.Address {
        continue
    }
    cfg.Bootstrap[i] = v
    i++
}
cfg.Bootstrap = cfg.Bootstrap[:i]</code>
Copy after login

In this code:

  • We initialize a variable i to 0, which represents the index position in the new, trimmed slice.
  • We iterate over each element of cfg.Bootstrap.
  • If an element matches both the user-supplied PeerID and Address, we skip it.
  • Otherwise, we copy the element to the ith position in the new slice.
  • We increment i to the next position.
  • After the loop, we assign the new slice to cfg.Bootstrap and truncate it to the correct length.

This approach ensures that all duplicate elements are removed and the slice remains consistent throughout the process. It avoids the index errors and panics that can occur when removing elements while iterating.

The above is the detailed content of How to Efficiently Remove Duplicate Items from a Slice in Go?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template