|
Interesting that this snippet: func (g *Gopher) DumpBinary(w io.Writer) error {
err := binary.Write(w, binary.LittleEndian, int32(len(g.Name)))
if err != nil {
return err
}
_, err = w.Write([]byte(g.Name))
if err != nil {
return err
}
err = binary.Write(w, binary.LittleEndian, g.Age)
if err != nil {
return err
}
return binary.Write(w, binary.LittleEndian, g.FurColor)
}
could be written like this: func (g *Gopher) DumpBinary(w io.Writer) {
binary.Write(w, binary.LittleEndian, int32(len(g.Name)))
w.Write([]byte(g.Name))
binary.Write(w, binary.LittleEndian, g.Age)
binary.Write(w, binary.LittleEndian, g.FurColor)
}
if the language supported exceptions. |
The substantive difference between Go and, e.g., Java with regard to exceptions is that Go builtin and standard library functions panic in a much narrower range of circumstances than Java's standard library. Go seems to prefer that the decision that an error condition is treated as a panic is generally left to user code that is written with more awareness of what is exceptional in the context of the role of that code than standard library code has.
So, you could write the code in pretty much exactly the way you propose in Go; you'd just need to write a wrapper function around binary.Write that panics on errors.