-2

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

user1722361
  • 377
  • 1
  • 4
  • 14
  • 4
    What do you mean by “get the type”? If there’s a type, it’s already declared, so why use `StructOf()`? – JimB Apr 21 '23 at 20:27
  • 1
    as the type-safe language, I don't know if it's not good to define type at the run time why do you want to do that? – ali heydarabadii Apr 22 '23 at 03:50

1 Answers1

0

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}
Zeke Lu
  • 6,349
  • 1
  • 17
  • 23