1

I want to define a struct completely dynamically, so that I can get the following struct, but without defining it first?

type Data struct {
   a string
   b int `json:"b"`
}
d := Data{}
5
  • 4
    What's the use case? Commented Aug 20, 2019 at 6:05
  • 1
    The main issue here is that you cannot, via reflection, set any unexported field (since Go 1.8). Since a and b are both unexported, you will only be able to create a zero-valued Data object. Commented Aug 20, 2019 at 6:08
  • 1
    Yes you can create structs via reflection. Commented Aug 20, 2019 at 6:10
  • 2
    The function godoc.org/reflect#StructOf will get you most of the way there. The unexported fields shown in the question are not supported. Commented Aug 20, 2019 at 6:25
  • 2
    I'm with @bereal here, why is this needed? There might be another way that doesn't rely on reflection and etc. Commented Aug 20, 2019 at 11:30

1 Answer 1

13

An application can create a struct programmatically using reflect.StructOf, but all fields in the struct must be exported.

The question gets the struct as a value, but it's likely that a pointer to the struct is more useful to the application.

Given the above, this answer shows how to do the following without defining the type at compile time:

type Data struct {
   A string `json:"a"`
   B int `json:"b"`
}
var d interface{} = &Data{}

The code is:

t := reflect.StructOf([]reflect.StructField{
    {
        Name: "A",
        Type: reflect.TypeOf(int(0)),
        Tag:  `json:"a"`,
    },
    {
        Name: "B",
        Type: reflect.TypeOf(""),
        Tag:  `json:"B"`,
    },
})
d := reflect.New(t).Interface()

Here's a runnable example that sets some fields: https://play.golang.org/p/uik7Ph8_BRH

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.