1# Custom types
2
3Custom types is a gogo protobuf extensions that allows for using a custom
4struct type to decorate the underlying structure of the protocol message.
5
6# How to use
7
8## Defining the protobuf message
9
10```proto
11message CustomType {
12  optional ProtoType Field = 1 [(gogoproto.customtype) = "T"];
13}
14
15message ProtoType {
16  optional string Field = 1;
17}
18```
19
20or alternatively you can declare the field type in the protocol message to be
21`bytes`:
22
23```proto
24message BytesCustomType {
25  optional bytes Field = 1 [(gogoproto.customtype) = "T"];
26}
27```
28
29The downside of using `bytes` is that it makes it harder to generate protobuf
30code in other languages. In either case, it is the user responsibility to
31ensure that the custom type marshals and unmarshals to the expected wire
32format. That is, in the first example, gogo protobuf will not attempt to ensure
33that the wire format of `ProtoType` and `T` are wire compatible.
34
35## Custom type method signatures
36
37The custom type must define the following methods with the given
38signatures. Assuming the custom type is called `T`:
39
40```go
41func (t T) Marshal() ([]byte, error) {}
42func (t *T) MarshalTo(data []byte) (n int, err error) {}
43func (t *T) Unmarshal(data []byte) error {}
44
45func (t T) MarshalJSON() ([]byte, error) {}
46func (t *T) UnmarshalJSON(data []byte) error {}
47
48// only required if the compare option is set
49func (t T) Compare(other T) int {}
50// only required if the equal option is set
51func (t T) Equal(other T) bool {}
52// only required if populate option is set
53func NewPopulatedT(r randyThetest) *T {}
54```
55
56Check [t.go](test/t.go) for a full example
57
58# Warnings and issues
59
60`Warning about customtype: It is your responsibility to test all cases of your marshaling, unmarshaling and size methods implemented for your custom type.`
61
62Issues with customtype include:
63  * <a href="https://github.com/gogo/protobuf/issues/199">A Bytes method is not allowed.<a/>
64  * <a href="https://github.com/gogo/protobuf/issues/132">Defining a customtype as a fake proto message is broken.</a>
65  * <a href="https://github.com/gogo/protobuf/issues/147">proto.Clone is broken.</a>
66  * <a href="https://github.com/gogo/protobuf/issues/125">Using a proto message as a customtype is not allowed.</a>
67  * <a href="https://github.com/gogo/protobuf/issues/200">cusomtype of type map can not UnmarshalText</a>
68  * <a href="https://github.com/gogo/protobuf/issues/201">customtype of type struct cannot jsonpb unmarshal</a>
69