Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
winstonpurnomo opened this issue Feb 19, 2024 · 3 comments
Closed

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

winstonpurnomo opened this issue Feb 19, 2024 · 3 comments

Comments

@winstonpurnomo
Copy link

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
Copy link

flimzy commented Feb 19, 2024

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
Copy link
Collaborator

dsnet commented Feb 20, 2024

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
Copy link
Collaborator

dsnet commented Feb 20, 2024

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

@dsnet dsnet closed this as completed Feb 20, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants