-2

I have this struct definition :

// Two columns, both strings.
type ExampleStructItem struct {
    Firstname string
    Surname string
}

and I have this slice of column names :

columns := []string{"Firstname", "Surname"}

and I am essentially trying to loop through my slice of column names, and then perform reflection on the corresponding struct to get information about the properties, such as their "Kind" etc.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
MickeyThreeSheds
  • 986
  • 4
  • 23
  • 42
  • 2
    You do reflection using the [`reflect`](https://golang.org/pkg/reflect) package. From your wording it seems like maybe you're already somewhat familiar with this. Have you tried any implementation? If so, can you post that code & what issues you had with it? – Adrian Dec 07 '18 at 16:56
  • 1
    Possible duplicate of https://stackoverflow.com/questions/18930910/access-struct-property-by-name. – Charlie Tumahai Dec 07 '18 at 16:58
  • @Adrian reflection is a totally new thing to me - I was able to do things like get the kind on a hard coded property of a struct - but I am totally unfamiliar with how I might get it by name like this - I've been unable to even get something to work at all. – MickeyThreeSheds Dec 07 '18 at 17:00
  • @ThunderCat - Not technically a duplicate - I saw this question before but it doesn't really talk about having a slice of columns to work with, and then trying to work with it to find the properties. – MickeyThreeSheds Dec 07 '18 at 17:01
  • 1
    @MickeyThreeSheds it gives you all the information you need to write your implementation. Just because a question isn't your *exact* scenario with an answer you can copy and paste into your code doesn't mean it isn't a valid duplicate. If you don't know how to loop over a slice, take the Tour of Go. – Adrian Dec 07 '18 at 17:03
  • @Adrian the poster below understood my question, and gave a working answer. It's pretty different to the other question. – MickeyThreeSheds Dec 07 '18 at 17:07

1 Answers1

1

Just use Type.FieldByName()

var ex ExampleStructItem
t := reflect.TypeOf(ex)

for _, name := range columns {

    field, ok := t.FieldByName(name)
    if ok {
        k := field.Type.Kind()
    } else {
        // error handling
    }

}

Playground

ssemilla
  • 3,900
  • 12
  • 28
  • Perfect! I will accept this as the best answer as soon as stack over flow lets me! Thankyou! – MickeyThreeSheds Dec 07 '18 at 17:07
  • Hey - sorry to bother you @ssemilla - Any chance that you might know how to set the falue of the property once we get it in this fashion? I am trying to learn reflection here - and I just don't grasp it right now! – MickeyThreeSheds Dec 07 '18 at 18:38
  • There is `Value.Set()`, I suggest you read https://blog.golang.org/laws-of-reflection but reflection should be your last resort. I often see people coming from dynamic languages not taking advantage of the type system and still solve everything like a hash map. – ssemilla Dec 08 '18 at 08:49