title: golang: pack a struct
body: <p>Please consider this sample go code:</p>
  
  <pre><code>package main
  
  //#include &lt;stdio.h&gt;
  //#include &lt;stdint.h&gt;
  //#pragma pack(push, 1)
  //struct Packed_Struct {
  //  uint16_t A;
  //  uint16_t B;
  //  uint32_t C;
  //  uint16_t D;
  //};
  //#pragma pack(pop)
  //
  //struct UnPacked_Struct {
  //  uint16_t A;
  //  uint16_t B;
  //  uint32_t C;
  //  uint16_t D;
  //};
  //
  //
  //void print_C_struct_size(){
  //  struct Packed_Struct Packed_Struct;
  //  struct UnPacked_Struct UnPacked_Struct;
  //  printf("Sizeof Packed_Struct: %lu\n", sizeof(Packed_Struct) );
  //  printf("Sizeof UnPacked_Struct: %lu\n", sizeof(UnPacked_Struct) );
  //  return;
  //}
  //
  import "C"
  
  
  
  import(
      "fmt"
      "unsafe"
  )
  
  type GoStruct struct{
      A   uint16
      B   uint16
      C   uint32
      D   uint16
  }
  
  
  func main(){
      fmt.Println("Hello world!")
      meh := C.print_C_struct_size()
      var GoStruct GoStruct
      fmt.Printf("Sizeof GoStruct : %d\n", unsafe.Sizeof(GoStruct) ) 
      fmt.Printf("meh type: %T\n", meh)
  }
  </code></pre>
  
  <p>The output is:</p>
  
  <pre><code>$ go run cgo.go 
  Hello world!
  Sizeof Packed_Struct: 10
  Sizeof UnPacked_Struct: 12
  Sizeof GoStruct : 12
  meh type: main._Ctype_void
  </code></pre>
  
  <p>Notice that the struct when packed takes 10 bytes, 12 otherwise. By default, my tries in Go seems to take 12 bytes as shown here. </p>
  
  <p>Is there a Go-ish way to pack this struct so it uses only 10 bytes? </p>