如何将切片结构转换为切片中的切片? [英] How to convert slice of structs to slice of strings in go?
问题描述
我有这个结构对象的一部分:
pre $
类型TagRow结构{
Tag1字符串
Tag2字符串
Tag3字符串
}
p>
[{abc} {def} {gh}]
我想知道如何将结果切片转换为一段字符串:
[abcdefgh]
我试图迭代,如:
for _,row:= range tagRows {
为_,t:=范围行{
fmt.Println(tag is,t)
}
}
但我得到:
不能超出行范围(类型TagRow)
感谢您的帮助。
对于您的具体情况,我只会手动进行:
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)
$ b $输出:
[abcdefgh 我]
如果您想让它动态遍历所有字段,可以使用< a href =https://golang.org/pkg/reflect/ =nofollow noreferrer> 反映
包。一个帮助函数可以做到这一点:
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)
输出相同:
[abcdefghi]
试试 Go Playground 。
查看类似的问题和更复杂的例子:
New go user here.
I have a slice of this struct objects:
type TagRow struct {
Tag1 string
Tag2 string
Tag3 string
}
Which yeilds slices like:
[{a b c} {d e f} {g h}]
I'm wondering how can I convert the resulting slice to a slice of strings like:
["a" "b" "c" "d" "e" "f" "g" "h"]
I tried to iterate over like:
for _, row := range tagRows {
for _, t := range row {
fmt.Println("tag is" , t)
}
}
But I get:
cannot range over row (type TagRow)
So appreciate your help.
解决方案 For your specific case I would just do it "manually":
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)
Output:
["a" "b" "c" "d" "e" "f" "g" "h" "i"]
If you want it to dynamically walk through all fields, you may use the reflect
package. A helper function which does that:
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
}
Using it:
var s2 []string
for _, v := range rows {
s2 = append(s2, GetFields(v)...)
}
fmt.Printf("%q\n", s2)
Output is the same:
["a" "b" "c" "d" "e" "f" "g" "h" "i"]
Try the examples on the Go Playground.
See similar questions with more complex examples:
Golang, sort struct fields in alphabetical order
How to print struct with String() of fields?
这篇关于如何将切片结构转换为切片中的切片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!