go-json-experiment / json

Experimental implementation of a proposed v2 encoding/json package
BSD 3-Clause "New" or "Revised" License
341 stars 11 forks source link

Why doesn't Unmarshal use generics to shorten syntax? #22

Closed winstonpurnomo closed 4 months ago

winstonpurnomo commented 4 months ago

We are all used to writing these four lines of code:

var name MyStruct
if err := json.Unmarshal(someBytes, &name); err != nil {
    ...
}

This was fine when Go was introduced, but nowadays with generics the standard library feels like it could be more ergonomic by replacing or adding a new Unmarshal func that can directly return a new object of some type without first declaring a zero value of that type.

name, err := json.UnmarshalDirectly[MyStruct](someBytes) 
flimzy commented 4 months ago

This would have at least one limitation that I would find problematic: Such a function would not allow unmarshaling into a pre-populated data structure.

dsnet commented 4 months ago

A more fair comparison is the following:

var name MyStruct
if err := json.Unmarshal(someBytes, &name); err != nil {
    ...
}

versus:

name, err := json.UnmarshalDirectly[MyStruct](someBytes) 
if err != nil {
    ...
}

It's not quite an apples-to-apples comparison if the error checking is kept in one example, but not the other.

In both cases, it's still 4 lines.

As @flimzy mentioned, we still need the non-generic variant for unmarshaling into a pre-populated value. Given that the generic variant doesn't provide much benefit, such proposals haven't quite stuck. For example, see golang/go#59053.

dsnet commented 4 months ago

I'm going to close this as there's a pre-existing upstream issue about this.