Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Program printing the wrong variable from channel

package main

import "fmt"

func main() {

    c := make(chan int, 5)
    c <- 5
    c <- 6
    close(c)
    fmt.Println(<-c)

}

shouldn’t the program above print 6 since it is the last value sent to the channel?

Whay is more, is it possible to print / receiving from a closed channel?

It prints 5

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Golang channels are FIFO, first in first out. That is why 5 gets printed out first.

EDIT: Closing channel indicates that no more data will be send to it.

"If a channel is closed, you can still read data. But you cannot send
new data into it. This program reads both before and after closing the
channel, which works. It’s closed only for sending"

https://golangr.com/close-channel/

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading