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

Add a way to distinguish thread safe and unsafe sets #131

Closed IceflowRE closed 8 months ago

IceflowRE commented 8 months ago

I would be nice to have a way to distinguish thread safe and unsafe sets. It would greatly improve the safety if i have to depend on a thread safe set and thus would disallow passing a thread unsafe set.

deckarep commented 8 months ago

Hello,

Do you have a proposal or example in mind?

Currently threadsafety is an internally managed and you have to choose what you need upfront during instantiation. Both safe and non-safe implement the same Set interface because they are fundamentally the same thing.

This is a decision that is made during the writing of code. So far this works well so long as the programmer understands what they are picking and why they want one over the other.

Maybe an example will help me grasp the issue or even better a proposal?

IceflowRE commented 8 months ago

TLDR: I think you might be right, it is up to the developer that he understand what to pick and to pass along. And that if a thread safe type is required to pass the correct thing. Especially if an interface is accepted.


Currently threadsafety is an internally managed and you have to choose what you need upfront during instantiation. Both safe and non-safe implement the same Set interface because they are fundamentally the same thing

This is the problem i had while thinking about a solution. An interface for each would be implemented by both.

This is a decision that is made during the writing of code. So far this works well so long as the programmer understands what they are picking and why they want one over the other.

The problem is if you expose the interface (mapset.Set) in a library and you have to trust the caller that he is passing a thread safe set, could be painful to debug and prevented beforehand.

My ideas so far.

  1. Expose the threadsafe and threadunsafe structs, so it is possible to check which is used.
    • This is not useful if someone implements an own set.
  2. Add a isThreadSafe() bool to the set interface.
    • will break compatibility
    • imho the main set interface should be free of implementation details
  3. Add a ThreadSafeSet interface which has another dummy method like to be distinguishable from the ThreadUnsafeSet which has another dummy method

In my eyes all ideas are not optimal.

Feel free to close this issue.

deckarep commented 8 months ago

Ok,

I’m going to close the issue and thank you for the response!