Skip to content

Preprocessor Directives

philhofer edited this page Nov 21, 2014 · 4 revisions

You can make tweaks to how the code generator generates methods using directives in your source code comments. All directives take the form

//msgp:directive [arg1] [arg2] [arg3]...

much like the gc compiler directives.

There are currently two supported directives.

Ingore
//msgp:ignore Type1 Type2 Type3

Ignore tells the code generator not to generate methods for the list of types supplied.

Shim
//msgp:shim Enum as:string using:(Enum).String/parseString

type Enum byte

const(
    A Enum = iota
    B
    C
    D
    invalid
)

func (e Enum) String() string {
    switch e {
    case A:
        return "A"
    case B:
        return "B"
    case C:
        return "C"
    case D:
        return "D"
    default:
        return "<invalid>"
    }
}

func parseString(s string) Enum {
    switch s {
    case "A":
        return A
    case "B":
        return B
    case "C":
        return C
    case "D":
        return D
    default:
        return invalid
    }
}

The shim directive lets you inline a type-conversion function for a user-defined type in order to have it encode and decode differently than the default for its concrete type. In the example above, we're using the shim directive to translate a const-iota block into strings for encoding and decoding. Note that the as: argument must take a "base" type (a built-in, []byte, interface{}, msgp.Extension or a type already processed by the code generator.)

Clone this wiki locally