首页 > 试题广场 >

考虑以下代码,关于 `select` 语句的行为,哪个描述是

[单选题]
考虑以下代码,关于 `select` 语句的行为,哪个描述是正确的?
ch := make(chan int, 1)
go func() {
    time.Sleep(2 * time.Second)
    <-ch
}()
ch <- 1
select {
case ch <- 2:
    fmt.Println("Sent 2 to channel")
default:
    fmt.Println("Default case executed")
}
  • 代码将打印 "Sent 2 to channel",因为 channel 是带缓冲的。
  • 代码将阻塞在 `select` 语句,直到 goroutine 从 channel 中读取值。
  • 代码将打印 "Default case executed",因为向已满的缓冲 channel 发送会立即失败。
  • 代码将引发 panic,因为试图向已满的 channel 发送数据。
这里没有for循环,里面caee只执行一次
发表于 今天 13:28:16 回复(0)