// Arrays and slices in Go // looking at them from the allocation perspective. // author: gtowell // Created: Nov 12, 2021 package main import ( "encoding/binary" "fmt" "unsafe" ) func main() { var aInt int = 5 var aInt8 int8 = 5 var aInt16 int16 = 5 fmt.Printf("%d %d %d\n", aInt, aInt8, aInt16) fmt.Printf("%d %d %d\n", unsafe.Sizeof(aInt), unsafe.Sizeof(aInt8), unsafe.Sizeof(aInt16)); // sizeof give the number of bytes used by the "top level descriptor" // binary.size the size of the contents of a slice var ar5Int16 [5]int16 fmt.Printf("Array of 5 int16 == %d total=%d\n", unsafe.Sizeof(ar5Int16), binary.Size(ar5Int16)) var ar5Int64 [5]int64 fmt.Printf("Array of 5 int64 == %d total=%d\n", unsafe.Sizeof(ar5Int64), binary.Size(ar5Int64)) var ar5x5Int64 [5][5]int64 fmt.Printf("Array of 5x5 int64 == %d total=%d\n", unsafe.Sizeof(ar5x5Int64), binary.Size(ar5x5Int64)) for i:=0; i<5; i++ { for j:=0; j<5; j++ { fmt.Printf("in 5x5 array%d %d %p\n", i, j, &ar5x5Int64[i][j]) } } var sl5Int16 []int16 = make([]int16, 5) fmt.Printf("slice of 5 int16 == %d total=%d\n", unsafe.Sizeof(sl5Int16),binary.Size(sl5Int16)) var sl5Int64 []int64 = make([]int64, 6) fmt.Printf("slice of 5 int64 == %d total=%d\n", unsafe.Sizeof(sl5Int64), binary.Size(sl5Int64)) }