title: golang casting byte array to struct
body: <p>I am looking for clean way to cast byte array to struct for client-server application.
  I know most ppl turn to gob package for this solution however I do not control the encoding for the application. that being said, I only programmed the server application not the client, there is a mutual contract for the protocol that is being exchanged.</p>
  
  <p>The best I could come out is the following.</p>
  
  <pre><code>type T struct {
      A int16
      B int8
      C []byte
  }
  
  func main() {
      // Create a struct and write it.
      t := T{A: 99, B: 10}
      buf := &amp;bytes.Buffer{}
  
      buf1 := []byte{5, 100, 100}
      fmt.Println(buf1)
  
      buf.Write(buf1)
  
      //err := binary.Write(buf, binary.BigEndian, t)
  
      //if err != nil {
      //  panic(err)
      //}
      fmt.Println(buf)
  
      // Read into an empty struct.
      t = T{}
      err := binary.Read(buf, binary.BigEndian, &amp;t)
      if err != nil {
          panic(err)
      }
      fmt.Printf("%d %d", t.A, t.B)
  }
  </code></pre>
  
  <p>However, as soon as number bytes does not coincide with the size of the struct, then go will send a panic. How can I modify this to work without the panic if undersize or oversize</p>
  
  <p><kbd><a href="http://play.golang.org/p/ZQOvQC4yPg" rel="nofollow">Go playground</a></kbd></p>