HiveBrain v1.2.0
Get Started
← Back to all entries
patterngoCritical

Is it OK to leave a channel open?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
leavechannelopen

Problem

Is it OK to leave a Go channel open forever (never close the channel) if I never check for its state? Will it lead to memory leaks? Is the following code OK?

func (requestCh chan<- Request) GetResponse(data RequestData) Response {
    reply := make(chan Response)
    requestCh <- Request{data: data, replyCh: reply}
    return <-reply
}

Solution

It's OK to leave a Go channel open forever and never close it. When the channel is no longer used, it will be garbage collected.


Note that it is only necessary to close a channel if the receiver is
looking for a close. Closing the channel is a control signal on the
channel indicating that no more data follows.


Design Question: Channel Closing

Context

Stack Overflow Q#8593645, score: 432

Revisions (0)

No revisions yet.