简体   繁体   English

当非默认是输入通道时,为什么 go 中的选择总是进入默认情况?

[英]Why a select in go always goes to default case when non default is a input channel?

I am new to go programming.我是编程新手。 Here is my piece of code.这是我的一段代码。 I am trying to assign value to a struct and assigning that struct to go channel.我正在尝试为结构分配值并将该结构分配给通道。 But it is not setting it and going to default case.但它没有设置它并进入默认情况。

package main
import (
    "fmt"
)
type object struct {
    a int
    b string
}
func main() {

    o1 := object{
        a: 25,
        b: "quack",
    }

    var oc chan object
    select {
    case oc <- o1:
        fmt.Println("Chan is set")
    default:
        fmt.Println("Chan is not set")
    }
}

You never initialized the oc channel, so it is nil , and sending on a nil channel blocks forever.您从未初始化oc通道,因此它是nil ,并且在nil通道上发送永远阻塞。 And the select statement chooses default if there are no ready cases.如果没有就绪情况,则select语句选择default

You have to initialize the channel.您必须初始化通道。 And if there are no receivers, it must have "some" buffer to accommodate the element you want to send on it, else the send would also block.如果没有接收器,它必须有“一些”缓冲区来容纳您要在其上发送的元素,否则发送也会阻塞。

This works the way you want it to (try it on the Go Playground ):这以您希望的方式工作(在Go Playground上尝试):

var oc chan object
oc = make(chan object, 1)

See related: How does a non initialized channel behave?请参阅相关: 非初始化通道的行为如何?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM