Golang Goroutine无尽循环内存泄漏

I have encountered strange (as for a man who is new to golang) behaviour of my goroutine:

go func(...) {
  for {
    buffer := make([]byte, 1024)
     ...
  } 
}

It slowly eats RAM. I understand that it is caused by calling make in an endless loop; it just allocates new memory every time. But i don't quite get why this construction:

  var buffer []byte
  for {
    buffer = make([]byte, 1024)
     ...
    }
  } 

..works well, while the first one doesn't. Shouldn't garbage collector detect that memory which old buf was pointing at is unreachable in both cases? And maybe there are some other similar traps that a go-newbie should know?

Also, if i will return this goroutine, will leaked memory be freed?

UPD: full memory leaking routine code:

go func(dataChannel chan []byte, errorChannel chan error) {
  for {
    buf := make([]byte, 1024)
    _, err := conn.Read(buf) 
    if err != nil {
      errorChannel<- err
      break
    }
    dataChannel<- buf
  } 
} (dataChannel, errorChannel)
  for {
        var mem runtime.MemStats
        runtime.ReadMemStats(&mem)
        fmt.Printf("alloc [%v] \t heapAlloc [%v] 
", mem.Alloc, mem.HeapAlloc)
        time.Sleep(2000 * time.Millisecond)
    }
  • added the above lines in your main function for loop (in the leaking code link given above)
  • new code : https://pastebin.com/UQbYuVN7
  • while running this shows that memory is being re-collected at regular intervals by gc

Thanks to JimB and his advice to set enviroment var GODEBUG=gctrace=1, i discovered that i had no env var GOGC set in my system, because of which garbage collector wasn't functioning at all. Setting it to default value was everything that i needed.