整数的通道切片

huangapple go评论84阅读模式
英文:

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 &lt;- 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 &lt;- 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 &lt;- 1
test &lt;- 2

Golang tour has an example:

https://tour.golang.org/concurrency/3

答案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 (
	&quot;fmt&quot;
)

func main() {
	c := make(chan []int)

	things := []int{1, 2, 3}

	go func() {
		c &lt;- things
	}()

	for _, i := range &lt;-c {
		fmt.Println(i)
	}

	go func() {
		c &lt;- append(things, 4)
	}()

	for _, i := range &lt;-c {
		fmt.Println(i)
	}
}

Output:

1
2
3
1
2
3
4

huangapple
  • 本文由 发表于 2017年4月14日 19:21:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/43410524.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定