首页 > 解决方案 > Go Reflection - 带有方法的动态类型

问题描述

使用 Go 的包,您可以使用reflect.StructOf()reflect创建动态结构类型:

typ := reflect.StructOf([]reflect.StructField{
        {
            Name: "Height",
            Type: reflect.TypeOf(float64(0)),
            Tag:  `json:"height"`,
        },
        {
            Name: "Age",
            Type: reflect.TypeOf(int(0)),
            Tag:  `json:"age"`,
        },
    })

有没有办法创建将这种新的动态类型作为接收器的函数/方法?具体来说,我想创建一个动态类型,使用StructOf()它实现一个接口(定义了几个方法),这样reflect.New(typ).Interface().(InterfaceType)会成功。

标签: gomethodsinterfacereflect

解决方案


推荐阅读