proposal: encoding/json: MustMarshal and MustUnmarshal #38519
Comments
How often does this really come up? When I want to set up a global variable containing JSON, which doesn't come all that often, I just do something like:
This is of course not possible with |
Using consts was the solution that I was using before, though interpolating strings with varaibles can lead to code that is pretty ugly in my opinion. I could go back to using strings here, for example var test_cases [][]byte = [][]byte{
util.MustMarshal(map[string]string{
"email": "fake@bar.com",
"password": password,
}),
util.MustMarshal(map[string]string{
"email": email,
"password": "fake",
}),
util.MustMarshal(map[string]string{
"email": email,
"secret": "fake",
}),
util.MustMarshal(map[string]string{
"email": email,
"password": password,
"secret": "fake",
}),
} Where |
I agree that these funcs would have a very limited usecase, but I would also think that it is a relatively simple implementation that is not backwards incompatible. It would panic presumable on programmer error, and save other tools from needing to add it to their projects |
I can see how it can be useful in some niche cases, but writing your own helper function is just a handful of lines. Backwards compatibility and simplicity are not the only factors for adding API to the standard library - see https://golang.org/doc/faq#x_in_std. These are just my thoughts, though. |
Since both
json.Marshal
andjson.Unmarshal
may return an error, it would be nice to extend those functions to functions that must complete, orpanic
. This is useful for declaringvar
s at the head of a file, or passing the result ofjson.MustMarshal
to a function as an argumentFor comparison, consider
regexp.MustCompile
where you mayand
The text was updated successfully, but these errors were encountered: