如何将结构切片转换为字符串切片?
How to convert slice of structs to slice of strings in go?
这里是新用户。
我有一部分这个结构对象:
type TagRow struct {
Tag1 string
Tag2 string
Tag3 string
}
产生的切片如下:
[{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)
非常感谢您的帮助。
对于你的具体情况,我会这样做 "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)
输出:
["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 上的示例。
使用更复杂的示例查看类似问题:
这里是新用户。 我有一部分这个结构对象:
type TagRow struct {
Tag1 string
Tag2 string
Tag3 string
}
产生的切片如下:
[{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)
非常感谢您的帮助。
对于你的具体情况,我会这样做 "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)
输出:
["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 上的示例。
使用更复杂的示例查看类似问题: