range 从channel 中取值

89 阅读1分钟

从有缓冲的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))

	}

总结: 两种取值方法能够打印出同样的效果

说明range 也可以从channel 中取走数据,就像<-channel一样

注: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 。