Why am i not able to send data in channel in case of select statement ? Please help

package main 

import (

func useChan(dataChan <-chan string,stopchan <-chan string){
			case <- dataChan:
				fmt.Println("data Recieved")
				time.Sleep(50 * time.Millisecond)
			case <- stopchan:

func main() {
	dataChan := make(chan string)
	stopchan := make(chan string)
	go useChan(dataChan,stopchan)
	//ready := true
	for timeout := time.After(5 *time.Second); ;{
		time.Sleep(10 * time.Millisecond)
		case dataChan <-"something":
		case <-timeout:
			stopchan <- "stop"
			fmt.Println("breaking ")


Please help me

What do you expect to happen? What happens instead? Do you get an error?

Ok , program ran but " data recieved " in the useChan function is not printing .
This is a learning exercise . There is some logical error.

I am expecting it to print "data recieved " . It is not printing. No error during running.

Take a look at the documentation for how to use time.After in a select:


ok , Thank you for your response, but apparently it worked when i changed the unbuffered channel to buffered channel with size 1.

dataChan := make(chan string,1)
stopchan := make(chan string,1)

But i don’t know the reason .
Can you please explain the behavior ? . Thank you

Try to remove both default cases from select blocks. And keep unbuffered channel.

OMG , it worked .

My explanation for it , please tell me if i am right or wrong.

Non buffered channel write are blocking unless there is some goroutine reading from it. Since “case selection” in Select statement is random if more than one case is true, it was selecting default case. But still , i don’t get why it was not reading from the “dataChan” even once if the probability of selecting between default and other channel is same.

Thank you

select case is pretty much random, but not completely :smiley:

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.