golang中单向channel的语法介绍
2017-07-27 11:31
639 查看
本文主要给大家介绍的是关于golang单向channel语法的相关内容,分享出来供大家参考学习,下面话不多说,来一起看看详细的介绍:
今天闲来无事补充一下golang的语法知识,想起来看看context的用法,结果碰到了一个没见过的channel语法:
// A Context carries a deadline, cancelation signal, and request-scoped values // across API boundaries. Its methods are safe for simultaneous use by multiple // goroutines. type Context interface { // Done returns a channel that is closed when this `Context` is canceled // or times out. Done() <-chan struct{} // Err indicates why this Context was canceled, after the Done channel // is closed. Err() error // Deadline returns the time when this Context will be canceled, if any. Deadline() (deadline time.Time, ok bool) // Value returns the value associated with key or nil if none. Value(key interface{}) interface{} }
注意看:
Done() <- chan struct{},一个接口函数的声明怎么这么奇怪呢?下面来分解一下。
Done() chan struct{}:如果函数定义改成这样,其意义是,
- 函数名Done,参数(),返回值
chan struct{}
。 - 单独拿返回值来说,它是一个管道chan,内部的数据类型是
struct{}
。 - 单独拿struct{}来说,我们熟悉
type Name struct{a int, b bool}
这样去定义一个结构体的类型,其实struct{…}就是定义结构体,和map[string]int这种定义是一样的,type只是给它启了一个别名。
<- chan struct{}:单独看这个表达式,我们知道如果
ch := make(chan struct{}),那么<- ch是从管道里取出数据。但是
chan struct{}是类型而不是变量,竟然能从一个类型里取数据??
其实
<-chan int仍旧是一个管道类型,它叫做单向channel。如果是
<-chan int,说明是只能读不能写的管道(也不能关闭),如果是
chan <- int,说明是只能写不能读的管道(可以关闭),仅此而已!
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者使用Go语言能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对脚本之家的支持。
您可能感兴趣的文章:
相关文章推荐
- Swift基础语法介绍
- golang中并发sync和channel
- HQL使用语法详细介绍
- Java 语法介绍(二):运算符
- thinkPHP 模板中的语法知识 详细介绍(十二)
- Oracle DECODE函数语法使用介绍
- Delphi基本之pascal语法(第一章.pascal介绍)
- charindex函数介绍, Case函数语法
- 1.CSS基础—介绍及语法
- golang语言并发与并行——goroutine和channel的详细理解(一)
- UI高级中关于Block的语法介绍
- Mac下安装golang介绍
- init.rc语法介绍
- golang中并发sync和channel
- Swift语法00.Swift 介绍
- Golang语法与代码格式速记【转】
- “单向网闸”技术介绍-网络隔离的新型产品
- WP7入门-XAML语法介绍
- 表单语法介绍
- golang的channel使用