I have an array that holds many objects. When I set the array to nil, will gc collect all the objects holded by the array?
package main
import (
"time"
"runtime"
)
type B struct {
bb []int
}
func NewB() *B {
return new(B)
}
func main() {
var bs = make([]*B, 10)
for i:=0; i<10; i++ {
bs[i] = NewB()
bs[i].bb = make([]int, 1000000)
}
time.Sleep(time.Second)
println("begin gc")
//for i:=0; i<10; i++ {
// bs[i] = nil
//}
bs = nil
runtime.GC()
time.Sleep(time.Second*2)
runtime.GC()
time.Sleep(time.Second*2)
}
First, I set bs = nil
, all the two gc infos show 76->76->76 MB
, this means gc does not free the memory.
Then, I add the for loop code in the slash statement, the first gc info shows 76->76->0 MB
, the second gc info shows 0->0->0 MB
.
So I'm confused that, when I set bs = nil
, there is no pointer referenced to all the objects, why gc does not free the objects? should all the objects explicitly set to nil?