title: How to gob encode struct with unexported pointer?
body: <p>I have a struct that I can successfully gob encode and decode as follows:</p>
  
  <pre><code>type Node struct {
      Value int
      Next  *Node
  }
  
  myNode := Node{
      Value: 1,
      Next: &amp;Node{
          Value: 2,
      },
  }
  var buf bytes.Buffer
  enc := gob.NewEncoder(&amp;buf)
  dec := gob.NewDecoder(&amp;buf)
  if err := enc.Encode(&amp;myNode); err != nil {
      panic(err)
  }
  var decodedNode Node
  if err := dec.Decode(&amp;decodedNode); err != nil {
      panic(err)
  }
  </code></pre>
  
  <p>I'd like to now hide the fields of <code>Node</code>:</p>
  
  <pre><code>type Node struct {
      value int
      next  *Node
  }
  </code></pre>
  
  <p>Because the fields are no longer exported I have to now write custom <code>GobEncode</code> and <code>GobDecode</code> functions:</p>
  
  <pre><code>func (d *Node) GobEncode() ([]byte, error) {
      var buf bytes.Buffer
      encoder := gob.NewEncoder(&amp;buf)
      if err := encoder.Encode(d.value); err != nil {
          return nil, err
      }
      if err := encoder.Encode(d.next); err != nil {
          return nil, err
      }
      return buf.Bytes(), nil
  }
  
  func (d *Node) GobDecode(b []byte) error {
      buf := bytes.NewBuffer(b)
      decoder := gob.NewDecoder(buf)
      if err := decoder.Decode(&amp;d.value); err != nil {
          return err
      }
      if err := decoder.Decode(&amp;d.next); err != nil {
          return err
      }
      return nil
  }
  </code></pre>
  
  <p>This doesn't work because of a nil value in <code>Node.next</code>:</p>
  
  <pre><code>panic: gob: cannot encode nil pointer of type *main.Node [recovered]
      panic: gob: cannot encode nil pointer of type *main.Node [recovered]
      panic: gob: cannot encode nil pointer of type *main.Node
  </code></pre>
  
  <p>I'm re-using <code>gob.NewEncoder</code> inside my custom function because I'm trying to re-use as much of the <a href="https://golang.org/src/encoding/gob/encode.go" rel="nofollow noreferrer">encode package</a> as possible.</p>
  
  <p>Any suggestions for getting this working?</p>