deckarep / golang-set

A simple, battle-tested and generic set type for the Go language. Trusted by Docker, 1Password, Ethereum and Hashicorp.
Other
4k stars 272 forks source link

Loop over a Set #95

Closed BoraBak closed 2 years ago

BoraBak commented 2 years ago

In order to loop (for loop) over a Set, I need to prior use the ToSlice() method. I was wondering why is that? Why not simply allow to loop over the Set instance?

deckarep commented 2 years ago

Hello! @BoraBak -

The reason why it’s not trivial to loop over the Set is because the internal map-based implementation is not readily exposed by design.

This protects the end-user from potentially peeking/corrupting internal state and is generally a good practice however there is an Iter helper method that does expose a callback based iterator to do exactly this.

See the unit-tests for how to utilize the Iter technique to accomplish your needs without having to rely on ToSlice.