forked from steger/pr3-sose2026
slice exercise
parent
ce34567ee0
commit
a6f88eeafd
|
|
@ -0,0 +1,31 @@
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"runtime"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
//create an array with a lot of data
|
||||||
|
massiveData := make([]int, 1_000_000)
|
||||||
|
for i := range massiveData {
|
||||||
|
massiveData[i] = i
|
||||||
|
}
|
||||||
|
|
||||||
|
// Task: Extract the first 8 elements safely
|
||||||
|
|
||||||
|
//1. attempt: use the slice operator
|
||||||
|
//smallSlice := massiveData[:8]
|
||||||
|
// consequence -> smallSlice and massiveData point to the same underlying array.
|
||||||
|
// Therefore, setting massiveData to nil is not sufficient to release that big array.
|
||||||
|
|
||||||
|
//2. attempt: create a new slice (with a new underlying array) and copy data
|
||||||
|
smallSlice := make([]int, 8)
|
||||||
|
copy(smallSlice, massiveData[:8])
|
||||||
|
|
||||||
|
massiveData = nil //don't use massive data anymore: Underlying array shall be freed.
|
||||||
|
runtime.GC() //run the garbage collector to make sure that all unused data is actually freed
|
||||||
|
|
||||||
|
//cap(smallSlice) should be 8 or similar, but not close to 1_000_000. The majority of the data should have been released by now
|
||||||
|
fmt.Printf("Small Slice: %v, Len: %d, Cap: %d\n", smallSlice, len(smallSlice), cap(smallSlice))
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue