I try to implement Sparse sets from this article in Go and make it into a package. In early implementation, the API is clean and minimal with only exported type Sparse
and exported method Insert
, Delete
, Has
, Union
, Intersection
, Clear
, and Len
, pretty much only basic sets operation.
Later on, I want to add new functionality, sets that can reserve an element automatically (lets call it AutoSparse
). If Sparse
have Insert(k int)
which insert k into sets, AutoSparse
have Reserved()
reserved an available element. If I have {0 1 2 4 5}
in AutoSparse
, when i call Reserve()
it must add 3, not 6 so now it become {0 1 2 4 5 3}
. Here's the implementation at playground.
As you can see, in order to maintain which element to added into sets, it doesn't add new field in the struct
and I want to keep it like that.
My Question is how to add that new functionality to my package without adding new exported type AutoSparse
to keep the API clean and minimal?
This is what i already try:
interface
to hide implementation but function signature is different, one use Insert(k int)
, the other use Reserve()
, even if I use name Insert()
it still different, or should I use Insert(k int)
but didn't use k
at all? it can but it's awkward.struct
to implement this because once you Use Reserve()
to add element, you can't use Insert(k int)
because it will messed up the reserved element, even Delete
and Clear
is different.You can use k... int
as parameter.
func (sparse Sparse) Insert(k... int) error {
if len(k) == 0 {
// first case
return nil
} else if len(k) == 1 {
// second case
return nil
} else {
return errors.New("Too many arguments")
}
}