I am writing a data serialisation module, and I found that "range” only supports builtin types such as string, list, and map.
This make me write a lot of repeated code like
var value interface{}
switch value.(type) {
case []interface{}:
foo := len(value.([]interface{})) // I really hate this
for index, value := range value.([]interface{}) {
// do something
}
case map[string]interface{}:
bar := len(value.(map[string]interface{})))} // I really hate this
for index, value := range value.(map[string]interface{}) {
// do other thing
}
}
I was wondering why Google implements it like this, why not just range over an interface that has Iter() function.
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
If you want you can create an iterator method that returns a channel, spawning a goroutine to write into the channel, then iterate over that with range. close() the channel on the write side when done. The channel will be GC'd once there are no references to it remaining. If you only keep a writable version of the channel in your goroutine,
it's possible the whole goroutine will be GC'd once there are no readable references to the channel. I'm not sure about that last part.
in fact, that is the biggest problem. losing type safety in range is not the way to go.
this issue has been discussed at length on this mailing list, please search the archive for prior threads.