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.
The above is the detailed content of How to Efficiently Remove Duplicate Peers from a Slice in Go?. For more information, please follow other related articles on the PHP Chinese website!