Compile error with slices of chan int


(James) #1

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.


(Ignacio Gómez) #2

The thing is indexchan[i] is indeed of type chan int, but you are trying to receive an int from it (<-indexchan[i] receives an int from the channel) and assign it to a string. That covers this type of error: cannot use <-indexchan[i] (type int) as type string in assignment.

As for cannot use a (type string) as type int in send, doSomeStuff receives c chan int, but you are tryng to send a string through it, which again is incorrect.

To summarize, when you declare a channel of some type, you may receive from or send through that channel only values of that type, and in your case you are mixing receiving an int into a string var, and trying to send a string through an int channel.


(James) #3

Oh ok! I totally misunderstood that, thanks for clearing it out! :slight_smile:


(system) #4

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.