Unlike C/C++, Go has GC, so we don’t need to handle memory allocation/release. However, we also should be cautious about memory leak.
Today, let’s see a memory leak case caused by slice
.
package mainimport (
"fmt"
)type Object struct {}func main() {
var a []*Object
for i := 0; i < 8; i++ {
a = append(a, new(Object))
} fmt.Println(cap(a), len(a)) // Output: 8, 8 a = remove(a, 5)