0

If I have the following declaration

type Foo struct {
   bar string
}

Can I use reflection to inspect the properties on the declaration without initialising it?

keys := reflect.something(Foo)

for _, key := range keys {
    fmt.Println(key) // "bar"
}

1 Answer 1

2

Use reflect.TypeOf to get the reflect.Type for Foo.

t := reflect.TypeOf(Foo{})

If you don't want to create a value of the type, then get the pointer type and "dereference" that type.

t := reflect.TypeOf((*Foo)(nil)).Elem()

The expression (*Foo)(nil) returns a nil pointer to the type. The Type.Elem method returns the pointed to type.

Iterate through the fields on the type. Type.NumField returns the number of fields on the type. Type.Field returns a StructField by field index.

for i := 0; i < t.NumField; i++ {
    fmt.Println(t.Field(i).Name)
}

Run it on the playground.

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.