【发布时间】:2023-03-23 07:48:01
【问题描述】:
我对使用反射生成的结构和普通结构之间的类型断言有疑问。
我知道这是一个非常有限的用例,但我仍然想知道为什么它不起作用。
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")
}
}
【问题讨论】:
标签: go struct reflection