armnotstrong
armnotstrong

Reputation: 9065

How to iterate through a struct in go with reflect

I have a specific struct that contains some url parameters, I want to build a url parameters string using reflect to iterate through the struct field, so that I wont care about what's the struct really contains.

Let's say I have a struct like this:

type Student struct {
   Name string `paramName: "username"`
   Age int `paramName: userage`
}

And I assign a student like this:

s := Student{
  Name : "Bob",
  Age : 15,
}

I want to build a query parameter string like this for this student instance:

username=Bob&userage=15

So far I have got:

func (s Student) buildParams() string {
    st := reflect.TypeOf(s)
    fieldCount := st.NumField()
    params := ""
    for i := fieldCount; i > 0 ; i-- {
      params = params +  "&" + st.Field(i).Tag.Get("paramName") + "=" + st.Field(i).Name
    }
    return params
}

But s.buildParams() gets me nothing, not event the tag value of paramName in each field :-(

So How can I do this?

Upvotes: 0

Views: 811

Answers (1)

Logiraptor
Logiraptor

Reputation: 1528

You shouldn't have a space between the colon and the value in the struct tags. paramName:"username" not paramName: "username". Also, you're using the field name instead of the field value. In order to turn the value into a string you'll need something a bit more complex. Here is a complete example: http://play.golang.org/p/4hEQ4jgDph

Upvotes: 1

Related Questions