2016-10-10 74 views
0

新用户在这里。 我有这样的结构对象的切片:如何将结构片转换为切片中的字符串片?

type TagRow struct { 
    Tag1 string 
    Tag2 string 
    Tag3 string 
} 

其中yeilds片,如:

[{a b c} {d e f} {g h}] 

我不知道我怎么能得到的片转换为字符串一样一片:

["a" "b" "c" "d" "e" "f" "g" "h"] 

我试图遍历,如:

for _, row := range tagRows { 
for _, t := range row { 
    fmt.Println("tag is" , t) 
} 

}

,但我得到:

cannot range over row (type TagRow) 

所以,感谢你的帮助。

+0

你可以试试[反映](https://golang.org/pkg/reflect/#example_StructTag)库。 – kichik

+0

@ kichik无法弄清楚如何。你能否详细说明你的答案? – Karlom

回答

3

针对您的特殊情况下,我只想做“手动”:

rows := []TagRow{ 
    {"a", "b", "c"}, 
    {"d", "e", "f"}, 
    {"g", "h", "i"}, 
} 

var s []string 
for _, v := range rows { 
    s = append(s, v.Tag1, v.Tag2, v.Tag3) 
} 
fmt.Printf("%q\n", s) 

输出:

["a" "b" "c" "d" "e" "f" "g" "h" "i"] 

如果你想让它动态地通过各个领域走,你可以使用reflect包。一个辅助功能,这是否:

func GetFields(i interface{}) (res []string) { 
    v := reflect.ValueOf(i) 
    for j := 0; j < v.NumField(); j++ { 
     res = append(res, v.Field(j).String()) 
    } 
    return 
} 

使用它:

var s2 []string 
for _, v := range rows { 
    s2 = append(s2, GetFields(v)...) 
} 
fmt.Printf("%q\n", s2) 

输出是一样的:

["a" "b" "c" "d" "e" "f" "g" "h" "i"] 

尝试在Go Playground的例子。

查看类似的问题更为复杂的例子:

Golang, sort struct fields in alphabetical order

How to print struct with String() of fields?