by mratzloff · 13y ago · 0 comments
Sure. Say you have a Set type (which is custom, since Go doesn't provide a `container/set` type.
type Set struct {
set map[interface{}]bool
}
All of the methods (`Add()`, `Contains()`, etc.) are going to be declared with `interface{}` parameters, e.g., func (set *Set) Add(x interface{}) bool
You would also want a method to get a slice of all members, e.g., func (set *Set) Members() []interface{}
If you want to use this as a set of strings, you would add without a cast: mySet.Add("foo")
However, when pulling it out you would need to cast it to a string. So if you were converting `[]interface{}` to `[]string`, it would look like this: values := make([]string, mySet.Len())
for i, member := range mySet.Members() {
values[i] = member.(string)
}I wrote a Cartesian product library that took a different tack--it splits the index and iterator cursor logic (integer fiddling) into one struct and the actual type into another, so it's easy to build type-checked objects.
In full disclosure, though, that was mainly because the alternative (using `interface{}`) was so utterly painful.