-
Notifications
You must be signed in to change notification settings - Fork 17.7k
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
proposal: encoding/json: add a generic Decode function #59053
Comments
I think I remember reading somewhere that the idea of APIs that take a pointer is that you can reuse the At the moment, you can't have generics on a method, and the design above has So I think you'd have to have the type on the This has the benefit of adding strong typing to the existing package main
import (
"encoding/json"
"fmt"
"io"
"log"
"strings"
)
type Data struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
r := strings.NewReader(`{ "name": "test", "age": 31 }`)
result, err := NewDecoder[Data](r).Result()
if err != nil {
log.Fatalf("failed to decode: %v", err)
}
fmt.Printf("name: %v\n", result.Name)
}
func NewDecoder[T any](r io.Reader) *Decoder[T] {
return &Decoder[T]{r: r}
}
type Decoder[T any] struct {
r io.Reader
}
func (d *Decoder[T]) Decode(v *T) error {
return json.NewDecoder(d.r).Decode(&v)
}
func (d *Decoder[T]) Result() (v T, err error) {
err = d.Decode(&v)
return
} |
Yes that's a good point, you would need a new Decoder type, unless we got #49085 first. |
Actually, my idea doesn't work for the existing API - https://go.dev/play/p/iRU0oLt4wPK This is because there's no way to have a constraint that enforces that a generic parameter is a struct as per the conversation here https://groups.google.com/g/golang-nuts/c/UxVAj75L-rg/m/raCOyQRjAAAJ |
https://go.dev/blog/when-generics
|
I'm not sure a generic variant provides sufficient benefit. Consider these two patterns: var v T
if err := dec.Decode(&v); err != nil {
...
} versus: v, err := dec.Decode[T]()
if err != nil {
...
} Both are 4 lines. |
I thinks this is error handling limitation, not generics. |
I think we should decline this for the same reason we should decline #57975 |
I believe with generics now in place a new more convenient
Decode
function could be added to theencoding/json
package, amongst otherencoding/*
packages.Proposed:
Existing:
The benefit of this API is not only is it more concise, but it removes the possibility of a
json: Unmarshal(nil)
error.The text was updated successfully, but these errors were encountered: