golang 只写 channel
时间: 2023-08-05 17:33:22 浏览: 67
在 Go 语言中,可以使用 `chan<-` 关键字来定义一个只写的 channel。只写 channel 可以用于向 channel 发送数据,但不能用于从 channel 中读取数据。下面是一个使用只写 channel 的示例:
```
func sendMessages(messages chan<- string, msgs []string) {
for _, msg := range msgs {
messages <- msg
}
close(messages)
}
func main() {
messages := make(chan string)
go sendMessages(messages, []string{"message 1", "message 2", "message 3"})
for msg := range messages {
fmt.Println(msg)
}
}
```
在 `sendMessages` 函数中,使用 `chan<-` 关键字来定义一个只写的 channel `messages`。在 `main` 函数中,我们创建了一个 `messages` 的 channel,然后启动了一个 goroutine 来向该 channel 中发送数据。在 `main` 函数中,我们使用 `range` 来遍历 `messages` 的 channel,并输出其中的数据。注意,在 `sendMessages` 函数中,我们在发送完所有消息后,使用 `close` 函数来关闭 `messages` 的 channel。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)