Skip to content
philhofer edited this page Dec 26, 2014 · 12 revisions

Serializing Foreign Types

Generating methods for a type defined outside the package in which you are currently working presents some challenges, as Go does not support defining methods for a type outside its originating package. There are, however, some workarounds:

  • You can specify -file in your //go:generate directive to be a foreign file (located somewhere else in your GOPATH), which will generate methods in the foreign package directly. Distributing such code would probably require maintaining a fork and/or git submodule.
  • You can define an identical struct type in your own package, and pointer-cast from the old type to the one defined in your package when you need to serialize.

Errors

All of the errors returned by the msgp package implement the msgp.Error interface. Thus, it is simple to distinguish between errors returned from encoding/decoding versus errors returned from other sources. Additionally, msgp errors will tell you whether or not the error allows the user to continue reading/writing to a stream. For example:

f, err := r.ReadFloat64()
if err != nil {
    if msgerr, ok := err.(msgp.Error); ok && msgerr.Resumable() {
        // the next object probably isn't a float64
    }
    // something else went wrong
    log.Fatalln("something broke:", err)
}
Clone this wiki locally