3

I have the following code

func f() {
  ...
  chan := make(chan error, 1)
  go func() {
    ...
    chan <- err
  }()

  err := other_method()
  if err != nil {
    log(err)
    return
  }

  err <- chan
  if err != nil {
    log(err)
  }
}

What will happen to the value written in the buffered channel if it is never ever read, because the func exited before reading from it? Is this a resource leak I need to care about?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
jdoe
  • 65
  • 5
  • 3
    Go is a memory managed language. When the reference to `chan` is dropped (i.e. at the end of `f`), the memory it takes can be freed by the garbage collector. There's no memory leak here. – Denys Séguret Jul 16 '19 at 12:56
  • Thanks for the quick answer :) – jdoe Jul 16 '19 at 12:57
  • 2
    Nope. When the channel goes out if scope it becomes garbage and thus doesn't reference the value anymore. No different from map or slice contents, or struct fields. – Peter Jul 16 '19 at 12:58
  • 2
    Note: there's a common misconception that once a channel is closed, it will be GC'ed. This is not the case. In the case of a buffered channel - any unread items - can still be read later (after the close event). As such, as others have mentioned, only when the last reference to the channel goes out of scope, will the channel's memory be reclaimed. – colm.anseo Jul 16 '19 at 13:24
  • 3
    Possible duplicate of [Is it OK to leave a channel open? ](https://stackoverflow.com/questions/8593645/is-it-ok-to-leave-a-channel-open) – Charlie Tumahai Jul 16 '19 at 13:27

0 Answers0