这里有新鲜出炉的 GO 语言教程,程序狗速度看过来!
Go 是一种新的语言,一种并发的、带垃圾回收的、快速编译的语言。Go 是谷歌 2009 年发布的第二款编程语言。2009 年 7 月份,谷歌曾发布了 Simple 语言,它是用来开发 Android 应用的一种 BASIC 语言。
通过消息来共享数据是 golang 的一种设计哲学,channel 则是这种哲理的体现。下面这篇文章主要给大家介绍了关于 golang 中单向 channel 语法的相关资料,文中通过示例代码介绍的非常详细,需要的朋友们下面来一起看看吧。
本文主要给大家介绍的是关于 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{}
。
- chan struct{}
。
- struct{}
这样去定义一个结构体的类型,其实 struct{…} 就是定义结构体,和 map[string]int 这种定义是一样的,type 只是给它启了一个别名。
- type Name struct{a int, b bool}
:单独看这个表达式,我们知道如果
- <- chan struct{}
,那么 <- ch 是从管道里取出数据。但是
- ch := make(chan struct{})
是类型而不是变量,竟然能从一个类型里取数据??
- chan struct{}
其实
仍旧是一个管道类型,它叫做单向 channel。如果是
- <-chan int
,说明是只能读不能写的管道(也不能关闭),如果是
- <-chan int
,说明是只能写不能读的管道(可以关闭),仅此而已!
- chan <- int
总结
来源: http://www.phperz.com/article/17/0822/344257.html