如何使用反射在Go语言中迭代遍历结构体。

huangapple go评论71阅读模式
英文:

How to iterate through a struct in go with reflect

问题

我有一个特定的结构体,其中包含一些URL参数,我想使用反射来遍历结构体字段,构建一个URL参数字符串,这样我就不用关心结构体实际包含的内容。

假设我有一个如下的结构体:

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

我像这样给一个学生赋值:

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

我想为这个学生实例构建一个查询参数字符串,像这样:

username=Bob&userage=15

到目前为止,我已经写了以下代码:

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
}

但是s.buildParams()没有返回任何结果,甚至没有返回每个字段中paramName的标签值 如何使用反射在Go语言中迭代遍历结构体。

那么我该如何解决这个问题呢?

英文:

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 如何使用反射在Go语言中迭代遍历结构体。

So How can I do this?

答案1

得分: 1

在结构标签中,冒号和值之间不应该有空格。应该是paramName:"username"而不是paramName: "username"。此外,你正在使用字段名称而不是字段值。为了将值转换为字符串,你需要使用稍微复杂一些的方法。这里有一个完整的示例:http://play.golang.org/p/4hEQ4jgDph

英文:

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

huangapple
  • 本文由 发表于 2015年2月28日 12:33:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/28778120.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定