Declare type dynamically in GoLang

65 Views Asked by At

I have a field struct type:

{
Name: "fieldA",
Type: "string",
}

and an array of this filed type:

[{
Name: "fieldA"
Type: "string"
},
{
Name: "filedB",
Type: "int",
}
...

This array may change or grow later.

Now I want to define a new struct type based on this array in runtime, like this:

type myStruct struct {
fieldA string,
fieldB int,
...
}

I think using reflection, I can get a myStruct instance by calling reflect.StructOf() but can I get the type? Is this possible?

Thanks

1

There are 1 best solutions below

0
Zeke Lu On

It seems that there is a misunderstanding here. reflect.StructOf() returns the struct type containing fields. It does not return "a myStruct instance". It looks like this is already the type you want to get, right?

This demo from the official document for reflect.StructOf should make it easy to understand the concepts:

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "reflect"
)

func main() {
    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"`,
        },
    })

    v := reflect.New(typ).Elem()
    v.Field(0).SetFloat(0.4)
    v.Field(1).SetInt(2)
    s := v.Addr().Interface()

    w := new(bytes.Buffer)
    if err := json.NewEncoder(w).Encode(s); err != nil {
        panic(err)
    }

    fmt.Printf("value: %+v\n", s)
    fmt.Printf("json:  %s", w.Bytes())

    r := bytes.NewReader([]byte(`{"height":1.5,"age":10}`))
    if err := json.NewDecoder(r).Decode(s); err != nil {
        panic(err)
    }
    fmt.Printf("value: %+v\n", s)
}

Output:

value: &{Height:0.4 Age:2}
json:  {"height":0.4,"age":2}
value: &{Height:1.5 Age:10}