I don’t think you understand what I’m talking about.
As I said above, it’s essentially because the underlying array of s has a pointer to A, so A can’t be reclaimed by GC memory, which is the simplest and clearest way to put it. So if the underlying array of s does not have a pointer to A, then A will be reclaimed by the GC memory, note that this is not an immediate collection, the GC has its own set of logic.
If you don’t set nil and S is used all the time, then A memory will never be reclaimed. (On this note, you can write a runtime to see the memory footprint of the sample code, it might be more intuitive to turn a into a long string)
var m runtime.MemStats
var a string
a = uuid.NewIdn(1024 * 1024)
fmt.Println(len(a)) //len 1024 * 1024
s := make([]*string, 2)
s[0] = &a
for i := 0; i < 10; i++ {
time.Sleep(100 * time.Millisecond)
runtime.ReadMemStats(&m)
fmt.Println(m.Alloc)
runtime.GC()
}
s[0] = nil //Please comment on this line repeatedly for comparison
s = s[1:] //Please comment on this line repeatedly for comparison
for i := 0; i < 10; i++ {
time.Sleep(100 * time.Millisecond)
runtime.ReadMemStats(&m)
fmt.Println(m.Alloc)
runtime.GC()
}
fmt.Println(s[0]) //Please comment on this line repeatedly for comparison
As for automation, no! I repeat, no!
Golang’s GC doesn’t automatically set up nil for you, and if it does, it will lead to a host of other problems, so the best thing to do is to do nothing and let the developers solve the problem themselves.