go两种遍历chan

  go中对通道chan遍历有两种方式一种是用range另一种为for select。

  

package main

import (
	"fmt"
	"strings"
)

func main() {
	intChan0 := make(chan int, 10)

	for i := 0; i < 10; i++ {
		intChan0 <- i
	}
	close(intChan0)

	for i := range intChan0 {
		fmt.Printf("range i value is %d, pointer is %d\n", i, &i)
	}

	fmt.Println(strings.Repeat("-", 20))

	intChan1 := make(chan int, 10)

	for i := 0; i < 10; i++ {
		intChan1 <- i
	}
	close(intChan1)

forLoop:
	for {
		select {
		case i, ok := <-intChan1:
			if !ok {
				break forLoop
			}
			fmt.Printf("for select i value is %d, pointer is %d\n", i, &i)
		}
	}

}

 上面打印结果为

range i value is 0, pointer is 824633794752
range i value is 1, pointer is 824633794752
range i value is 2, pointer is 824633794752
range i value is 3, pointer is 824633794752
range i value is 4, pointer is 824633794752
range i value is 5, pointer is 824633794752
range i value is 6, pointer is 824633794752
range i value is 7, pointer is 824633794752
range i value is 8, pointer is 824633794752
range i value is 9, pointer is 824633794752
--------------------
for select i value is 0, pointer is 824633794760
for select i value is 1, pointer is 824633794768
for select i value is 2, pointer is 824633794776
for select i value is 3, pointer is 824633794784
for select i value is 4, pointer is 824633794792
for select i value is 5, pointer is 824633794800
for select i value is 6, pointer is 824633794808
for select i value is 7, pointer is 824633794816
for select i value is 8, pointer is 824633794824
for select i value is 9, pointer is 824633794832

 使用golang版本为1.21,可以看出,rang读取chan内元素,其指针一样,for select每次不同。

通常情况下,当有其他for select有其他case分支使用for select。

  

posted @ 2024-01-23 17:02  ALXPS  阅读(111)  评论(0编辑  收藏  举报