samedi 20 juin 2020

Is it possible to provide a Name to a Dynamically created Struct (using Reflection) in Golang

I've a dynamically created struct and I would like to provide a Name to this struct. Is it possible to do that?

// Test ...
type Test struct {
    Name string
}

func main() {
    structFields := []reflect.StructField{
        {
            Name: "Name",
            Type: reflect.TypeOf(""),
        },
    }
    // Provide a Name to this structDec 
    structDec := reflect.StructOf(structFields)

    fmt.Printf("\nType Dynamic : %+v\n", structDec)
    fmt.Printf("\nType Test : %+v\n", reflect.TypeOf(Test{}))
}

This prints

Type Dynamic : struct { Name string }

Type Test : main.Test
  1. Is it possible to set a Name such as Test1 to the Dynamic Struct structDec?
  2. How does go derive the struct Name? I see during dynamic struct creation the str value (which is the same value in the output) is set in reflect.structType, Is this how the Name is calculated for Dynamic Struct's?

Go Playground : https://play.golang.org/p/8ra2pXZIHgp





Aucun commentaire:

Enregistrer un commentaire