"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Efficiently Remove Duplicate Peers from a Slice in Go?

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

Published on 2024-11-17
Browse:122

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

Removing Duplicate Items from a Slice

Given a text file containing a list of peers represented as objects with "Address" and "PeerID" attributes, the task is to remove all duplicate peers based on matching "Address" and "PeerID" from the "Bootstrap" slice in the code's configuration.

To achieve this, we iterate through each peer object in the slice multiple times. During each iteration, we compare its "PeerID" and "Address" with the user-supplied values. If a match is found, we remove that specific object from the slice. This process ensures that all instances of the peer are removed.

However, there is an edge case to consider. If the last peer in the "Bootstrap" slice is a duplicate, the code will panic with a "slice bounds out of range" error. To address this issue, we can implement a more robust solution that copies non-matching values to the beginning of the slice and trims the excess when the iteration is complete.

Here's the updated code:

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]

This code iterates through the "Bootstrap" slice. For each peer object, it compares its "PeerID" and "Address" with the user-supplied values. If the peer is not a duplicate, it is copied to the beginning of the slice at index "i." The "i" index is then incremented to point to the next available position.

Once the iteration is complete, the "Bootstrap" slice is trimmed to remove any excess elements, effectively removing all duplicate peers including the last one.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3