deckarep / golang-set

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

Helpers to transform between types #70

Closed dray92 closed 2 years ago

dray92 commented 4 years ago

Currently, methods like ToSlice() return a slice of interface objs, which makes sense.

In practice, we find ourselves having to write multiple helpers to go from interface slices to primitives like strings, int, etc., whether it be for using NewSetFromSlice, or ToSlice.

Is value in added a set of helpers under the mapset package to support transformations between core primitive types, and interface{}?

(I am happy to contribute.)

shreve commented 3 years ago

My personal preference is to have the code accepting the data to handle the conversion, so in the case of ToSlice(), it's pretty easy for your application to do a type assertion or switch statement, so I think that's on you.

for _, el := range set.ToSlice() {
   thing := el.(string)
    switch el.(type) {
    case string:
        #
    }
}

On the other hand, converting your application's slices into interface slices as you describe for NewSetFromSlice is pretty annoying. I resolved this in the above PR by accepting an interface rather than a slice of interfaces and sorting it out with the reflection library, which was already included by the threadUnsafeSet.

deckarep commented 2 years ago

Closing due to no activity on this.