Okay, I didn't explain that well... :-)

I'm tinkering with reflective meta-programming, and I need some way to
reference source-code elements.

In order to get a type, reflect.TypeOf(Foo{}) is type-safe - Foo is checked
at compile-time.

If you have an instance of a struct, you can reference it's methods quite
easily and then use reflection on those, and that's type-safe - the
method-name is checked at compile-time.

But it appears there is no type-safe way to reference a field? Using e.g.
reflect.TypeOf(Foo{}).FieldByName("xyz") the field-name "xyz" is just a
string and goes unchecked at compile-time.

So what I'm looking for, is some way to reference the actual field, not
it's value, in a type-safe way.

I'm a bit puzzled as to why e.g. the following doesn't mean anything:

type Person struct {
     Name string

field := Person.Name // doesn't work

Or possibly something along the lines of:

field := typeof(Person.Name)

Or some kind of typeof-like operator.

If nothing exists, do you think I would get anywhere with a feature request?

On Tue, Dec 31, 2013 at 8:10 PM, andrey mirtchovski
your question is unclear: are you asking whether go supports type
assertions (http://golang.org/ref/spec#Type_assertions) or are you
trying to figure out if particular type satisfies an interface
(http://golang.org/doc/faq#guarantee_satisfies_interface)? either way
an interface must be involved, otherwise you already have all
necessary tools to answer the question "does struct X have field XYZ"
at compile time.

can you give an example?
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Search Discussions

Discussion Posts


Follow ups

Related Discussions



site design / logo © 2022 Grokbase