I want to create a slice that is a channel and contains integers.
test := make(chan []int)
test <- 5
This is the way I initialized it but I have no idea how to now pass a value since for slices we would use append but for channels we send data using <-
I have tried with both just <- and append and both combined like below and can't get it to work
test <- append(test, 5)
You defined a channel of []int
but are trying to send it an int
. You have to send it a slice of ints and then have the receiver use that slice.
A working example is here: https://play.golang.org/p/TmcUKU8G-1
Notice that I'm appending the 4 to the things
slice and not the channel itself
package main
import (
"fmt"
)
func main() {
c := make(chan []int)
things := []int{1, 2, 3}
go func() {
c <- things
}()
for _, i := range <-c {
fmt.Println(i)
}
go func() {
c <- append(things, 4)
}()
for _, i := range <-c {
fmt.Println(i)
}
}
Output:
1
2
3
1
2
3
4
This is called
buffered channel
the right syntaxis is
test := make(chan int, 5)
test <- 1
test <- 2
Golang tour has an example: