Hello,
I am writing my first go program and I’ve met with a compile error I don’t understand. Here’s a modified snippet of my code that can reproduce the problem:
package main
import "fmt"
func main() {
var list1 []string
var indexchan []chan int
item := "dummy"
i := 0
for ; i < 10; i++ {
list1 = append(list1, item)
// make 1 goroutine w/ 1 unique per iteration
c := make(chan int)
indexchan = append(indexchan, c)
go doSomeStuff(c)
if item == "" {
// in my code "item" is a variable reassigned every loop
// and passed to doSomeStuff to be processed
fmt.Println("nil encountered, breaking...")
break
}
}
list2 := make([]string, i)
list3 := make([]string, i)
var item2 string
var item3 string
for i := range list1 {
item2 = <-indexchan[i]
item3 = <-indexchan[i]
list2[i] = item2
list3[i] = item3
}
}
func doSomeStuff(c chan int) {
a := "result1"
b := "result2"
c <- a
c <- b
}
Using “go run” returns:
tmp.go:34:9: cannot use <-indexchan[i] (type int) as type string in assignment
tmp.go:35:9: cannot use <-indexchan[i] (type int) as type string in assignment
tmp.go:44:4: cannot use a (type string) as type int in send
tmp.go:45:4: cannot use b (type string) as type int in send
For some reason “indexchan[i]”, which is supposed to be an index of a slice of chan int, is recognized as a type int. After tweaking that code a bit to have it compile and with the help of reflect.TypeOf its seems thought that indexchan and indexchan[i] are nonetheless respectively of type “[]chan int” and “chan int”.
So any ideas on why does this error occur?
Thanks.