Me: “uughh I wish Go had code generation macros, I need to do a whole pile of tedious implementations”
Also me: “Wait, I have an idea. Hold my beer!”
30 minutes later:
#!/bin/sh # # Me: Can we have code generation macros? # Go: We have macros at home # The code generation macros at home: # # Implements MarshalBinary on top of AppendBinary marshal_binary_append() { cat <<EOF // MarshalBinary is equivalent to calling AppendText(nil) func (v $1) MarshalBinary() ([]byte, error) { return v.AppendBinary(nil) } EOF } # Implements (Append/Marshal/Unmarsha)lBinary for one byte structures marshal_binary_byte() { marshal_binary_append $1 cat <<EOF // Appends the single-byte binary representation of $1 to buf func (v $1) AppendBinary(buf []byte) ([]byte, error) { return append(buf, byte(v)), nil } // Unmarshals $1 from a single-byte buffer func (v *$1) UnmarshalBinary(buf []byte) error { if len(buf) != 1 { return errors.New("expected 1 byte input for UnmarshalBinary on $1") } *v = $1(buf[0]) return nil } EOF } exec >marhsal.gen.go echo '// Generted by gen/marshal.sh. DO NOT EDIT.' echo 'package foo' echo '' ... marshal_binary_append Foo ...