I'm trying to implement a type related collection, logic is very
simple like below.
1. Creates a vector.
2. When user tries to add a struct to it, check whether duplicate one
exists, if not add it.
Then I found out that I have to copy-paste similar logic each time
when creating an new type related collection. I felt very bad about
this, but without generic support or C++ like inherit, I cannot figure
out a better approach to solve this. I thought about to use reflect,
but the code turns very ugly.
Any good idea about how to deal with this situation?
Personally, I'd generate a unique key for each struct instance and use a map. If you need an ordered list, then the map could store a linked list element or a slice index instead of the struct itself. You'll still have some duplicated code, but not nearly as much.
Also, the container/vector package is deprecated. Use slices and append instead.
-Daniel
How about something like:
type Value interface{}
func (c *Collection) AnyEqual(v Value, cmp func(a, b Value) bool) bool {
for _, item := range c {
if cmp(item, v) {
return True
}
}
return False
}
Then using the function inside Attach() with appropriate closures? The
AnyEqual method specifies the algorithm, the cmp function passed
specifies the mechanism.
--
Dr Rich Wareham
The Search and Sort functions in the sort package are the classic
binary search and quicksort algorithms that are examples of code that
is generic in the "applies to different types" sense without being
generic in the "C++ templates" sense.
See $GOROOT/src/pkg/sort/{search,sort}.go.
It would be interesting to see your tests -- since slice+append can
do (most of) what container/vector/Vector does and has less overhead,
I would have thought it would have been faster.
It's being deprecated because once append was added to Go, the
main use of Vector -- easily pushing elements on the end -- was
subsumed; there isn't enough functionality left to justify having
(and maintaining) the package.
Chris
--
Chris "allusive" Dollin
Most of the functionality of the container/vector package can be
replicated using append and copy.