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:
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]
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.
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