August 2019
Beginner to intermediate
798 pages
17h 2m
English
The example in this section will use a slice to store a large amount of structures. Each structure stores two integer values. The Go code sliceGC.go is as follows:
package main
import (
"runtime"
)
type data struct {
i, j int
}
func main() {
var N = 40000000
var structure []data
for i := 0; i < N; i++ {
value := int(i)
structure = append(structure, data{value, value})
}
runtime.GC()
_ = structure[0]
}
The last statement (_ = structure[0]) is used for preventing the garbage collector from garbage collecting the structure variable too early, as it is not referenced or used outside of the for loop. The same technique will be used in the three Go programs that follow. Apart from this important detail, a for loop is used for putting ...
Read now
Unlock full access