The size in bytes of the fragment content

I am trying to send some data to OpenGl. Sending an array is easy thanks to Sizeof:

array := [...]Whatever {lots of data} array_ptr := gl.Pointer(&array[0]) array_size := gl.Sizeiptr(unsafe.Sizeof(array)) gl.BufferData(gl.ARRAY_BUFFER, array_size, array_ptr, gl.STATIC_DRAW) 

I would like to use slices instead of arrays because the size of my 3D models is unknown at compile time.

How to get the size in bytes of the slice content? I thought about this:

 size := uintptr(len(slice)) * unsafe.Sizeof(slice[0]) 

but he is not very general. In fact, I need to know the base type of the slice for this to work, and this assumes that all elements of the array are the same size.

I could also iterate over the whole fragment and add all the sizes of each element. It is not very fast.

I am ready to always keep len (s) == cap (s), can this help me?

Edit: implementing a proposed solution using a run-time display

 package main import "fmt" import "reflect" func ElemSize(container interface{}) uintptr { return reflect.TypeOf(container).Elem().Size() } func ElemSizeVerbose(container interface{}) uintptr { t := reflect.TypeOf(container) e := t.Elem() s := e.Size() fmt.Println(t, e, s) return s } func main() { a := [...]int8{2, 3, 5, 7, 11} // Array s := []int64{2, 3, 5, 7, 11} // Slice z := []int32{} // Even empty things ElemSizeVerbose(a) // [5]int8 int8 1 ElemSizeVerbose(s) // []int64 int64 8 ElemSizeVerbose(z) // []int32 int32 4 } 
+4
source share
1 answer

In a slice or array, each element always has the same size. Therefore, your example will work as long as len (s)> 0. In other words, as long as the slice has at least one element in it. Otherwise, it will panic.

To avoid having to have an element in a slice, I recommend using the following:

  uintptr(len(s)) * reflect.TypeOf(s).Elem().Size() 
+6
source

All Articles