Go 只读/只写channel
2015-06-01 21:46
1276 查看
Go中channel可以是只读、只写、同时可读写的。
//定义只读的channel
read_only := make (<-chan int)
//定义只写的channel
write_only := make (chan<- int)
//可同时读写
read_write := make (chan int)
定义只读和只写的channel意义不大,一般用于在参数传递中,见代码:
如果将上面send方法和recv方法中的参数对调:
func send(c <-chanint) {
func recv(c chan<- int) {
编译就会报错:
./channel.go:18: invalid operation: c <- i (send to receive-only type <-chan int)
./channel.go:24: invalid operation: range c (receive from send-only type chan<- int)
//定义只读的channel
read_only := make (<-chan int)
//定义只写的channel
write_only := make (chan<- int)
//可同时读写
read_write := make (chan int)
定义只读和只写的channel意义不大,一般用于在参数传递中,见代码:
package main import ( "fmt" "time" ) func main() { c := make(chan int) go send(c) go recv(c) time.Sleep(3 * time.Second) } //只能向chan里写数据 func send(c chan<- int) { for i := 0; i < 10; i++ { c <- i } } //只能取channel中的数据 func recv(c <-chan int) { for i := range c { fmt.Println(i) } }
如果将上面send方法和recv方法中的参数对调:
func send(c <-chanint) {
func recv(c chan<- int) {
编译就会报错:
./channel.go:18: invalid operation: c <- i (send to receive-only type <-chan int)
./channel.go:24: invalid operation: range c (receive from send-only type chan<- int)
相关文章推荐
- go os/exec执行外部程序
- Go signals 信号
- Go 环境变量相关操作
- Go命令行参数解析flag包
- setjmp和longjmp goto应用
- 1.2 reverse a C-Style String
- 解決google在scroll裡左右拖動的問題
- GoogleCodeJam2015第二轮
- Go的pprof使用
- Golang Channel用法简编
- 一个有关Golang变量作用域的坑
- Goroutine是如何工作的
- Go语言是如何处理栈的
- django中url,静态文件,POST请求的配置
- django中url,静态文件,POST请求的配置
- Go语言学习笔记(一) : 搭建Windows下的Go开发环境
- mode_t 内核文件权限值 S_IRUGO=S_IRUSR | S_IRGRP | S_IROTH
- WordPress-当文章属于两个或多个分类时,使其在不同的分类使用不同文章模板的方法
- 探寻Google Photos无限免费的“真相”