英文:
Channel slice of integers
问题
我想创建一个包含整数的通道切片。
test := make(chan []int)
test <- 5
这是我初始化的方式,但是我不知道如何传递值,因为对于切片,我们会使用append,但是对于通道,我们使用<-发送数据。
我尝试过只使用<-,也尝试过使用append,还尝试过两者结合,但都无法使其正常工作。
test <- append(test, 5)
英文:
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)
答案1
得分: 1
这被称为“缓冲通道”。
正确的语法是:
test := make(chan int, 5)
test <- 1
test <- 2
Golang tour有一个例子:
https://tour.golang.org/concurrency/3
英文:
This is called
> buffered channel
the right syntaxis is
test := make(chan int, 5)
test <- 1
test <- 2
Golang tour has an example:
答案2
得分: 1
你定义了一个 []int
类型的通道,但是尝试向它发送一个 int
类型的值。你需要发送一个整数切片,并让接收方使用该切片。
一个可工作的示例代码在这里:https://play.golang.org/p/TmcUKU8G-1
请注意,我将 4 添加到了 things
切片中,而不是通道本身。
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)
}
}
输出结果:
1
2
3
1
2
3
4
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论