by lolpanda · 1mo ago · 0 comments
Not necessarily. Among other things, MarshalJSON methods called during marshaling can return an error for whatever reason the developer sees fit - one possibility that comes to mind is that part of the object tree being marshalled is lazily loaded, and failed to do so.
And, as others have mentioned, there are types like "any" whose marshalability can't be determined at compile time. Those types aren't necessarily at the top level, either; they could appear anywhere in the object tree.
Because they are common types, makes sense to precautionary have the error return.
Plus the point of the marshal interface is that it’s reusable.
If you wanted type safety with JSON in Go then don’t use the marshal interface. Period.
And even for unmarshalling you could get a compile time error if you try to unmarshall to a type that doesn't support it.