Here is my note on json & struct, run it somewhere and it may give you a 
hint.

package main

import "fmt"
import "encoding/json"

type prices struct{
    Price   float64 `json:"price"`
    floor   float64
    Ceiling float64
    settle  float64
    time    int64
}


func main() {
    content := prices{
        Price:  6.4 , 
        floor:  3.5, 
        Ceiling:    7, 
        settle: 8.5,
        time:   1,
    }
    
    js,_ := json.Marshal( content)
    fmt.Println(string(js))

    var back prices
    json.Unmarshal(js, &back)
    fmt.Println(back)
    fmt.Println(back.Price)
}

在2022年4月14日星期四 UTC+8 16:51:22<Sebastien Binet> 写道:

> hi there,
>
> I am playing a bit with generics.
> I am trying to implement a parametrized "Read" function that unmarshals
> bytes into some type value that implements an interface:
>
> type T1 struct {
> v string
> }
>
> func (t *T1) UnmarshalBinary(p []byte) error {
> t.v = string(p)
> return nil
> }
>
> type Unmarshaler interface {
> UnmarshalBinary(p []byte) error
> }
>
> func f1[T Unmarshaler](p []byte) (T, error) {
> var t T
> err := t.UnmarshalBinary(p)
> return t, err
> }
>
> func main() {
> p := []byte("hello")
> t1, err := f1[T1](p)
> if err != nil {
> log.Panic(err)
> }
>
> log.Printf("t1: %+v", t1)
> }
>
> my naive attempt failed like so:
>
> ./prog.go:26:16: T1 does not implement Unmarshaler (UnmarshalBinary method 
> has pointer receiver)
>
> it's only when I rewrite my f1 function like so that it "works":
>
> func f2[T any](p []byte) (t T, err error) {
> switch t := any(&t).(type) {
> case Unmarshaler:
> err = t.UnmarshalBinary(p)
> default:
> panic("boo")
> }
> return t, err
> }
>
> but it doesn't take advantage of the nice type constraints Go's generics
> provide.
>
> of course, replacing:
> t1, err := f1[T1](p)
>
> with:
> t1, err := f1[*T1](p)
> compiles. but fails at runtime.
>
> what am I missing?
> how do I convey the constraint "unmarshaling usually imply passing a
> pointer to some value" ?
>
> -s
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/1679908f-db42-4eb7-88d9-1efc95ef7bbbn%40googlegroups.com.

Reply via email to