From 33a964af7d94a4003a5e1063073ff59cd4470baa Mon Sep 17 00:00:00 2001 From: Andrew Mains Date: Tue, 9 Feb 2021 17:50:20 -0700 Subject: [PATCH] Document pitfall with custom marshal/unmarshal implementations I ran into what felt like a "gotcha" around custom marshal/unmarshal behavior today where `easyjson` continued generating MarshalEasyJSON and UnmarshalEasyJSON methods for my types even though I had defined them on my struct already, resulting in method redeclaration errors: ``` ./foo_easyjson.go:13:6: method redeclared: MyStruct.MarshalEasyJSON method(*MyStruct) func(*jwriter.Writer) method(MyStruct) func(*jwriter.Writer) ./foo_easyjson.go:14:20: (*MyStruct).UnmarshalEasyJSON redeclared in this block previous declaration at ./foo.go:16:6 ``` These were confusing to me, as I assumed that `easyjson` would check if the methods existed already before generating them. Once I thought it through, it was simple enough to work around with an //easyjson:skip; I documented that approach to hopefully save others (including future me ;)) time. There's probably a fix that could be applied within the code itself (i.e. don't generate if the method's defined), but I figure this is a quick fix. --- README.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/README.md b/README.md index 952575b9..f5f77782 100644 --- a/README.md +++ b/README.md @@ -136,6 +136,14 @@ that satisfy the `easyjson.Marshaler` / `easyjson.Unmarshaler` interfaces. These will be used by `easyjson.Marshal` and `easyjson.Unmarshal` when defined for a Go type. +Note: easyjson does not currently skip code generation for types which already define their own `MarshalEasyJSON`/`UnmarshalEasyJSON` +functions, meaning that code generation will result in duplicate method errors like: + +`(*MyStruct).UnmarshalEasyJSON redeclared in this block` + +This can be avoided by excluding types with custom marshalling behavior from easyjson code generation, either using +`//easyjson:skip` (with `-all`) or by simply not including them in the `easyjson` invocation. + Go types can also satisfy the `easyjson.Optional` interface, which allows the type to define its own `omitempty` logic.