-3

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")
    }
}
Angel F Syrus
  • 1,984
  • 8
  • 23
  • 43
pavan
  • 11
  • 2
  • 3
    Any `case` in a select happens only if it _can_ happen. If there is nobody to read from your oc (or in your case even worse you do not have a made oc) the default happens. The Tour of Go explains this in detail. – Volker Aug 26 '19 at 07:10

1 Answers1

7

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?

icza
  • 389,944
  • 63
  • 907
  • 827