Program printing the wrong variable from channel


package main

import "fmt"

func main() {

    c := make(chan int, 5)
    c <- 5
    c <- 6


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


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"

Answered By – StefanR

Answer Checked By – Katrina (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.