logoalt Hacker News

lolpanda • yesterday at 6:42 PM • 9 replies • view on HN

the marshal api has been very annoying. why does marshal return an error? the only reason the marshal can return an error is that the input type is not marshalable. it's certainly a code bug. to me it's like int+str returning an error instead of compiler error


Replies

duskwuff • yesterday at 7:44 PM

> why does marshal return an error? the only reason the marshal can return an error is that the input type is not marshalable

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.

sgsjchs • yesterday at 7:36 PM

Types may be mostly marshallabble, have a subset of values that are unmarshallable. E.g. non-finite floats.

hnlmorg • yesterday at 6:48 PM

I wouldn’t class unmarshallable data as a compile time error.

Plus the point of the marshal interface is that it’s reusable.

➕ show 1 reply
bicarbonato • yesterday at 8:20 PM

AFAIK it's mostly because of floats. JSON doesn't support `NaN` and `infinity` for example.

Because they are common types, makes sense to precautionary have the error return.

0x696C6961 • yesterday at 7:38 PM

Then write yourself a MustMarshal wrapper that panics.

➕ show 2 replies
leetrout • yesterday at 6:50 PM

JSON is a runtime input of unknown type but in your example those are known types so the compiler can catch them.

lolpanda • yesterday at 7:37 PM

i meant i hoped it's panic as opposed to return an error. if there was an error, how am i supposed to handle it? can i tell the user hey sorry my bad it's likely a code error? crash is better than possible eating the error siliently

iaaan • yesterday at 7:24 PM

It is trivial to ignore an error in Go if you know your use case cannot result in one. But at the end of the day, json.Marshal takes an `any` as a parameter, so it must return an error.

NoDodgeQuestion • yesterday at 7:13 PM

do not know at compile time that input is not marshalable, every language marshal must return error for this reason, not only golang