Go:select时,如果通道已经关闭会怎么样?

1.for循环里被关闭的通道

package main

import (
	"fmt"
	"time"
)

func main() {
	c := make(chan int)
	go func() {
		time.Sleep(time.Second)
		c <- 10
		close(c)
	}()
	for {
		select {
		case x, ok := <-c:
			fmt.Println(x, ok)
			time.Sleep(500 * time.Millisecond)
		default:
			fmt.Println("xxx")
			time.Sleep(500 * time.Millisecond)
		}
	}
}
xxx
xxx
10 true
0 false
0 false
0 false
0 false

2.怎么样才能不读关闭后通道

package main

import (
	"fmt"
	"time"
)

func main() {
	c := make(chan int)
	go func() {
		time.Sleep(time.Second)
		c <- 10
		close(c)
	}()
	for {
		select {
		case x, ok := <-c:
			fmt.Println(x, ok)
			time.Sleep(500 * time.Millisecond)
			if !ok {
				c = nil
			}
		default:
			fmt.Println("xxx")
			time.Sleep(500 * time.Millisecond)
		}
	}
}

3.如果select里只有一个已经关闭的case,会怎么样?

package main

import (
	"fmt"
	"time"
)

func main() {
	c := make(chan int)
	go func() {
		time.Sleep(time.Second)
		c <- 10
		close(c)
	}()
	for {
		select {
		case x, ok := <-c:
			fmt.Println(x, ok)
			time.Sleep(500 * time.Millisecond)
		}
	}
}

10 true
0 false
0 false
0 false
0 false

4.select里只有一个已经关闭的case,置为nil,会怎么样?

panic
posted @ 2024-11-01 14:31  朝阳1  阅读(2)  评论(0编辑  收藏  举报