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

Patricia Arquette
Release: 2024-11-02 01:53:02
Original
756 people have browsed it

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

Deleting Duplicates from a Slice

You aim to remove duplicate peers from a text file where each peer is characterized by an Address and PeerID. The provided code effectively tackles this task but encounters an error when deleting the last duplicate. To resolve this, a revised approach is presented.

To begin, declare a variable i and initialize it to 0. This variable will track the index of the last non-duplicate peer in the cfg.Bootstrap slice. Then, loop through the slice using a range-based for loop.

Within the loop, check if the current peer's Address and PeerID match those of the peer to be removed. If they do, skip the current peer. Otherwise, assign the current peer to cfg.Bootstrap[i] and increment i.

After the loop has finished, cfg.Bootstrap[i:] will contain only the duplicate peers that need to be removed. To trim these excess values, assign cfg.Bootstrap[:i] back to cfg.Bootstrap.

Here's the revised code snippet:

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

This revised approach efficiently deletes all duplicate peers, including those in the last position.

The above is the detailed content of How to Efficiently Remove Duplicate Entries 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!