title: Efficient Go serialization of struct to disk
body: <p>I've been tasked to replace C++ code to Go and I'm quite new to the Go APIs. I am using gob for encoding hundreds of key/value entries to disk pages but the gob encoding has too much bloat that's not needed.   </p>
  
  <pre><code>package main
  
  import (
      "bytes"
      "encoding/gob"
      "fmt"
  )
  type Entry struct {
      Key string
      Val string
  }
  
  func main() {
      var buf bytes.Buffer
      enc := gob.NewEncoder(&amp;buf)
      e := Entry { "k1", "v1" }
      enc.Encode(e)
      fmt.Println(buf.Bytes())
  }
  </code></pre>
  
  <p>This produces a lot of bloat that I don't need:</p>
  
  <pre><code>[35 255 129 3 1 1 5 69 110 116 114 121 1 255 130 0 1 2 1 3 75 101 121 1 12 0 1 3 86 97 108 1 12 0 0 0 11 255 130 1 2 107 49 1 2 118 49 0] 
  </code></pre>
  
  <p>I want to serialize each string's len followed by the raw bytes like:</p>
  
  <pre><code>[0 0 0 2 107 49 0 0 0 2 118 49]
  </code></pre>
  
  <p>I am saving millions of entries so the additional bloat in the encoding increases the file size by roughly x10.</p>
  
  <p>How can I serialize it to the latter without manual coding?</p>