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
> 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.
Types may be mostly marshallabble, have a subset of values that are unmarshallable. E.g. non-finite floats.
I wouldn’t class unmarshallable data as a compile time error.
Plus the point of the marshal interface is that it’s reusable.
It could be if go had a more powerful type system.
This isn’t a type system problem. It’s a data origin problem. Ie it could be any random JSON blob a user entered. The compiler doesn’t know this ahead of time.
If you wanted type safety with JSON in Go then don’t use the marshal interface. Period.
loading story #50370622
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.
JSON is a runtime input of unknown type but in your example those are known types so the compiler can catch them.
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
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.
do not know at compile time that input is not marshalable, every language marshal must return error for this reason, not only golang