1

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

Kishore Bandi
  • 5,537
  • 2
  • 31
  • 52
  • 2
    Printf can also give you the typename: https://play.golang.org/p/QBhcGAn2bSn, what should answer Nr. 2. The answer to 1. is no, because that type is not availiable at compile time. You are creating this at runtime. – apxp Jun 20 '20 at 09:05
  • I'm not so sure about Number 2. Check the `Printf(%T)` it prints `reflect.Type` for both compiled and dynamic structs. https://play.golang.org/p/L61aA2io651 Yeah for No 1, I guessed the same. But looks like inside reflect.structOf they do try to figure out a name for the struct, its just no exposed to the developer. – Kishore Bandi Jun 20 '20 at 09:11
  • 2
    `StructOf` creates an anonymous type. The type's name cannot be set. The type's name matches the names of static anonymous types. See https://play.golang.org/p/fcc9EhGOnEL. –  Jun 20 '20 at 12:50
  • @iLoveReflection hmm, I thought so. Any idea on how to get this Dynamic Struct working with Gorm? When I use this struct as a field in other structs then Gorm is unable to figure out the name, so falls back to empty string causing the DDL/DML statements to fail. I'm hitting a brick wall with all solutions, only option left is to write a DB Wrapper to handle these cases manually. – Kishore Bandi Jun 20 '20 at 18:22

0 Answers0