range 从 channel 中取值

从有缓冲的channel 中取值

func main() {

	c := make(chan int, 20)
	func() {
		for i := 0; i < 10; i++ {
			c <- i
			fmt.Println("len:", len(c))
		}
		close(c)
	}()

}

使用range 取值

range channel 能够从channel缓冲区中取值


	for n := range c {
		fmt.Println(n)
		//len(c) 表示channel 缓冲区中的数量
		fmt.Println("len:", len(c))
	}

遍历判断取值

	for v, ok := <-c; ok; v, ok = <-c {
		fmt.Println(v)
		fmt.Println("len:", len(c))

	}

总结:
两种取值方法能够打印出同样的效果
注:len(通道) 标志通道中元素的个数

func len(v Type) int

The len built-in function returns the length of v, according to its type:
Array: the number of elements in v.
Pointer to array: the number of elements in *v (even if v is nil).
Slice, or map: the number of elements in v; if v is nil, len(v) is zero.
String: the number of bytes in v.
Channel: the number of elements queued (unread) in the channel buffer;
         if v is nil, len(v) is zero.
For some arguments, such as a string literal or a simple array expression, the result can be a constant. See the Go language specification's "Length and capacity"

Channel :通道缓冲区中排队(未读)的元素数;
如果 v 是 nil,,则 len(v) =0 。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值