title: Can go protobuf marshal message to an already allocated byte array without copy?
body: <p>I am implementing client server communication by self defined packets.
  I am using Go <code>net.conn</code>. It can dial tcp/unix schemes which is very convenient. I use <code>protocol buffer</code> to define my messages.</p>
  
  <p>I defined a Packet which contains <code>length</code> and <code>buffer</code>  </p>
  
  <pre><code>type Packet struct {
      length uint32
      buffer []byte
  }
  </code></pre>
  
  <p>The API function is like this:<br>
  <code>func(api *API) Send(m *proto.Message) error</code><br>
  <code>func(api *API) Receive(p *Packet) error</code></p>
  
  <p>Take <code>send</code> function as an example, it takes in a protobuf message, marshal it into <code>Packet</code>. And write it to the <code>net.conn</code>. </p>
  
  <p>Here is a simplified version of the Send function:</p>
  
  <pre><code>func(api *API) Send(m *proto.Message) error {
      bytes, err := proto.Marshal(m)
      if err != nil {
          return err
      }
      buffer := api.packet[:length]
      copy(buffer, bytes)
      _, err := api.conn.Write(buffer)
      if err != nil {
          return err
      }
      return nil
  }
  </code></pre>
  
  <p>I was copying <code>bytes</code> into <code>buffer</code>. Because Go protocol buffer API only provides<br>
   <code>func Marshal(pb Message) ([]byte, error)</code></p>
  
  <p>In protocol buffer C++, it provides
  <code>bool SerializeToArray(void * data, int size) const</code>, which is serializing the message and storing it in the given byte array.
  But I can not find the same thing in Go protocol buffer API.</p>
  
  <p>Is there any way to avoid the copy if I want to directly storing serialized result in the given byte array? </p>