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. And the select
statement chooses default
if there are no ready cases.
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):
var oc chan object
oc = make(chan object, 1)
See related: How does a non initialized channel behave?