Solution: Memory Handling

Let's look at the solution.

We'll cover the following...

Solution

Press + to interact
package main
import (
"runtime"
"testing"
)
const megabyte = 1024 * 1024
func TestAllocations(t *testing.T) {
count := 10
arr := make([][]int, count)
for i := 0; i < count; i++ {
newarr := make([]int, 0, megabyte)
for k := 0; k < megabyte; k++ {
newarr = append(newarr, k)
}
arr2 := make([]int, 2)
copy(arr2, newarr[0:2])
arr[i] = arr2
}
// for test purposes, run garbage collector to clean up unused memory
runtime.GC()
// check how much memory this program is still using
var m runtime.MemStats
runtime.ReadMemStats(&m)
if m.Alloc/megabyte >= 1 {
t.Error("there is too much memory allocated")
}
// check if the array has expected data
for i, a := range arr {
if len(a) != 2 || a[0] != 0 || a[1] != 1 {
t.Errorf("Array item #%v does not have valid data", i)
}
}
}

Explanation

  • In line 16: make() was used with one argument, which
  • ...