lundi 8 juin 2020

Golang Type assert ad-hoc struct to concrete struct

I have a question about type assertions between a struct generated with reflect and a normal struct.

I know that this is a very limited use cases, but I would still like to know why it won't work.

https://play.golang.org/p/Ko7e8ysgjCk

package main

import (
    "fmt"
    "math/big"
    "reflect"
)

type TupleT struct {
    X *big.Int
    Y *big.Int
}

func main() {
    var fields []reflect.StructField
    fields = append(fields, reflect.StructField{
        Name: "X",
        Type: reflect.TypeOf(new(big.Int)),
        //Tag:  reflect.StructTag("json:\"" + "x" + "\""),
    })
    fields = append(fields, reflect.StructField{
        Name: "Y",
        Type: reflect.TypeOf(new(big.Int)),
        //Tag:  reflect.StructTag("json:\"" + "y" + "\""),
    })
    a := reflect.New(reflect.StructOf(fields)).Elem().Interface()
    if _ = a.(TupleT); true {
        fmt.Println("Hello, playground")
    }

    b := new (struct {X *big.Int "json:\"x\""; Y *big.Int "json:\"y\""})
    interf2 := interface{}(b)
    if _ = interf2.(*TupleT); true {
        fmt.Println("Hello, playground")
    }
}




Aucun commentaire:

Enregistrer un commentaire