It's actually a fairly obvious reason. Because the container doesn't
know what value type is in the interface{}.
You'll notice that IntVector.Iter() and StringVector .Iter() actually
do return a chan int and chan string respectfully.
- jessta
--
=====================
http://jessta.id.au
I am sorry, I did not formulate my question precisely enough:
What I meant is:
"Why does the iterating mechanism make use of channels at all ?"
(Why is the use of channels to iterate over a container considered
advantageous ?)
Channels are concurrency-safe. You could call vector.Iter() get the
channel and pass it to a bunch of worker goroutines
that can each range over it and each get different items to process,
which is kind of cool.
It also means you don't really need to exposure the underlying data
structure too much. You can range over an slice but it might get a bit
messy if another goroutine wanted to modify that slice while you were
ranging over it. The channel means these kind of issues can be wrapped
up in someway.
Because it is trying to implement exp/iterable's Iterable interface.
You don't have to use Iter to range over a vector.
for i, val := range vec
for i, val := range vec.Data()
both avoid the goroutine and channel.
Russ
The package exp/iterable, like everything in exp, is experimental.
There are beautiful and elegant programs one can write using explicit
data streams. Doug McIlroy's power series work, both the
Newsqueak and Haskell implementations, is one common example.
Here's another common example: given two binary trees, check
whether the sets defined by the two binary trees match.
Recursion is a great way to traverse one binary tree, by letting
the stack, stack pointer, and program counter do the lifting,
but it fails if you have two to traverse simultaneously... unless
you have two stacks, stack pointers, and program counters,
in which case you can do two recursions at once, in different goroutines.
[http://c2.com/cgi/wiki?SameFringeProblem]
Try to code the binary tree example without goroutines + channels,
or compare the recursive traversal with the implementation of the
C++ STL map::iterator, and you'll see the advantage. But they
do have a cost and they don't make sense for everything.
Walking a slice is one of those things.
Ultimately I think the exp/iterable package is a failed experiment,
or at least an unfortunate distraction, because it has led people to
use goroutines for walking through a slice, which is a bit like
hunting sparrows with a cannon. When a goroutine is really needed,
it's just as easy, and typically more convenient, to return a
chan int directly and not worry about the iterable package.
Russ