title: De- and encode interface{} with Gob
body: <p>I'm trying to de- and encode a struct which contains a Interface{} as field. </p>
  
  <p>The problem there is, that the encoding works fine, but if I try to decode the data to <code>data</code> the value gets <code>{ &lt;nil&gt;}</code>.</p>
  
  <p>It actually works, if I change <code>Data interface{}</code> to <code>Data substring</code>, but this is not a solution for me because I want to cache the results of a query to a database which have different types depending on the query. (e.g. <code>Users</code> or <code>Cookies</code>)</p>
  
  <h1>Minimal working example</h1>
  
  <h2>Source</h2>
  
  <p><a href="http://play.golang.org/p/aX7MIfqrWl" rel="noreferrer">http://play.golang.org/p/aX7MIfqrWl</a></p>
  
  <pre><code>package main
  
  import (
      "bytes"
      "encoding/gob"
      "fmt"
  )
  
  type Data struct {
      Name string
      Data interface{}
  }
  
  type SubType struct {
      Foo string
  }
  
  func main() {
      // Encode
      encodeData := Data{
          Name: "FooBar",
          Data: SubType{Foo: "Test"},
      }
      mCache := new(bytes.Buffer)
      encCache := gob.NewEncoder(mCache)
      encCache.Encode(encodeData)
  
      fmt.Printf("Encoded: ")
      fmt.Println(mCache.Bytes())
  
      // Decode
      var data Data
      pCache := bytes.NewBuffer(mCache.Bytes())
      decCache := gob.NewDecoder(pCache)
      decCache.Decode(&amp;data)
  
      fmt.Printf("Decoded: ")
      fmt.Println(data)
  }
  </code></pre>
  
  <h2>Outputs</h2>
  
  <h3>Expected output</h3>
  
  <p>Encoded: [37 255 129 3 1 1 4 68 97 116 97 1 255 130 0 1 2 1 4 78 97 109 101 1 12 0 1 4 68 97 116 97 1 255 132 0 0 0 29 255 131 3 1 1 7 83 117 98 84 121 112 101 1 255 132 0 1 1 1 3 70 111 111 1 12 0 0 0 19 255 130 1 6 70 111 111 66 97 114 1 1 4 84 101 115 116 0 0]</p>
  
  <p>Decoded: {FooBar {Test}}</p>
  
  <h3>Current Result</h3>
  
  <p>Encoded: [37 255 129 3 1 1 4 68 97 116 97 1 255 130 0 1 2 1 4 78 97 109 101 1 12 0 1 4 68 97 116 97 1 255 132 0 0 0 29 255 131 3 1 1 7 83 117 98 84 121 112 101 1 255 132 0 1 1 1 3 70 111 111 1 12 0 0 0 19 255 130 1 6 70 111 111 66 97 114 1 1 4 84 101 115 116 0 0]</p>
  
  <p>Decoded: { }</p>