title: Size in bytes of the content of a slice
body: <p>I am trying to send some data to OpenGl.  Sending an array is easy thanks to Sizeof:</p>
  
  <pre><code>array := [...]Whatever {lots of data}
  array_ptr := gl.Pointer(&amp;array[0])
  array_size := gl.Sizeiptr(unsafe.Sizeof(array))
  gl.BufferData(gl.ARRAY_BUFFER, array_size, array_ptr, gl.STATIC_DRAW)
  </code></pre>
  
  <p>I would like to use slices instead of arrays because the size of my 3D models is not known at compile time.</p>
  
  <p><strong>How do I retrieve the size, <em>in bytes</em>, of the content of a slice?</strong>  I thought of this:</p>
  
  <pre><code>size := uintptr(len(slice)) * unsafe.Sizeof(slice[0])
  </code></pre>
  
  <p>but it is not very general.  Indeed, I need to know the underlying type of the slice in order for this to work, and this supposes that all the elements of the array have the same size.</p>
  
  <p>I could also loop over the whole slice and add all the sizes of every element.  It's not very fast.</p>
  
  <p>I am ready to always keep the len(s)==cap(s), can that help me?</p>
  
  <p><strong>Edit: implementation of the proposed solution using runtime reflection</strong></p>
  
  <pre><code>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
  }
  </code></pre>