I'm trying to pass the results of munging a slice into a channel. Here's the obviously broken version. I've tried a few ways of doing it that don't seem to work well. I'm looking for an idiomatic way of tackling this.
func gen() <-chan []int {
c := make(chan []int)
go func(c chan []int) {
defer close(c)
s := []int{0, 1, 2, 3}
for i := 0; i < len(s); i++ {
s[i] = -1
c <- s
}
}(c)
return c
}
func main() {
for s := range gen() {
fmt.Println(s)
}
}
Result:
[-1 -1 2 3]
[-1 -1 2 3]
[-1 -1 -1 -1]
[-1 -1 -1 -1]
It does not work because the underlying array is the same. So you are modifying the same memory.
Here is a working example. Copy the memory at each round.
http://play.golang.org/p/OXfKVg8ZlZ
package main
import "fmt"
func gen() <-chan []int {
c := make(chan []int)
go func(c chan []int) {
defer close(c)
s := []int{0, 1, 2, 3}
for i := 0; i < len(s); i++ {
s[i] = -1
newSlice := make([]int, len(s))
copy(newSlice, s)
c <- newSlice
}
}(c)
return c
}
func main() {
for s := range gen() {
fmt.Println(s)
}
}
Output
[-1 1 2 3]
[-1 -1 2 3]
[-1 -1 -1 3]
[-1 -1 -1 -1]