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>
In this code:
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!