Junior — Middle
Kas Go-s võib tekkida olukord, kus mäluressursid ei vabastata ja see põhjustab lekked?
sobes.tech AI
Vastus AI-lt
In Go, memory leaks are possible, although the language has an built-in garbage collector that automatically frees unused memory. However, leaks can occur if the program continues to hold references to objects that are no longer needed, for example:
- Global variables or slices to which elements are added but not removed.
- Channels that are not closed and continue to hold data.
- Closures that capture large structures and are not released.
Therefore, leaks in Go are often more related to the program's logic than to low-level memory management errors, and to logic that prevents the garbage collector from freeing objects.
Example:
var cache = make(map[string]*Data)
func addToCache(key string, data *Data) {
cache[key] = data // If the cache is not cleared, data will remain in memory
}
If the cache is not cleared, objects within it will not be released, leading to increased memory consumption.