Golang 向已关闭的chan读写数据会怎样

1. 向已关闭的chan写

会直接panic,报 send to close channel错误

package main

func main() {
	// 创建缓冲区为4的字符串chan
	schoolChan := make(chan string, 4)
	// 放入3个值
	schoolChan <- "国防科大"
	schoolChan <- "北京大学"
	schoolChan <- "湖南大学"

	// 关闭chan
	close(schoolChan)

	// 尝试写数据,会panic: send to close channel
	schoolChan <- "中南大学"
}

2. 向已关闭的chan读

会返回2个值,若已关闭的chan中还存在值,第二个值为true,第一个值为对应的chan中的值,若已关闭的chan中不存在值,第二个值为false,第一个值为对应chan类型的零值

package main

import "fmt"

func main() {
	// 创建缓冲区为4的字符串chan
	schoolChan := make(chan string, 4)
	// 放入3个值
	schoolChan <- "国防科大"
	schoolChan <- "北京大学"
	schoolChan <- "湖南大学"

	// 关闭chan
	close(schoolChan)

	// 向已关闭的chan读
	if school, isEmpty := <-schoolChan; isEmpty {
		fmt.Println("school:", school)
	}

	// 向已关闭的chan读
	if school, isEmpty := <-schoolChan; isEmpty {
		fmt.Println("school:", school)
	}

	// 向已关闭的chan读
	if school, isEmpty := <-schoolChan; isEmpty {
		fmt.Println("school:", school)
	}

	// 向若chan不存在元素,则第二个参数的值为 false
	if school, isEmpty := <-schoolChan; isEmpty {
		fmt.Println("school:", school)
	}
}
  • 使用for循环遍历chan,若chan未关闭则会堵塞等待chan放入元素,如chan关闭则取出chan内所有元素并终止循序
package main

import (
	"fmt"
)

func main() {
	// 创建缓冲区为4的字符串chan
	schoolChan := make(chan string, 4)
	// 放入3个值
	schoolChan <- "国防科大"
	schoolChan <- "北京大学"
	schoolChan <- "湖南大学"

	// 关闭chan
	close(schoolChan)

	// for循环遍历channel,会将已关闭的chan中缓冲区的数据取出完后终止循序
	for school := range schoolChan {
		fmt.Println("school:", school)
	}
}

posted @ 2024-02-02 21:06  梦_鱼  阅读(100)  评论(0编辑  收藏  举报