go - 如何在go中将结构切片转换为字符串切片?

Kar*_*lom 2 struct go slice

新用户在这里。我有这个结构对象的一部分:

type TagRow struct {
    Tag1 string  
    Tag2 string  
    Tag3 string  
}
Run Code Online (Sandbox Code Playgroud)

其中 yields 切片如下:

[{a b c} {d e f} {g h}]
Run Code Online (Sandbox Code Playgroud)

我想知道如何将结果切片转换为字符串切片,例如:

["a" "b" "c" "d" "e" "f" "g" "h"]
Run Code Online (Sandbox Code Playgroud)

我试着像这样迭代:

for _, row := range tagRows {
for _, t := range row {
    fmt.Println("tag is" , t)
}
Run Code Online (Sandbox Code Playgroud)

}

但我得到:

cannot range over row (type TagRow)
Run Code Online (Sandbox Code Playgroud)

所以感谢你的帮助。

icz*_*cza 5

对于您的具体情况,我只会“手动”执行此操作:

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)
Run Code Online (Sandbox Code Playgroud)

输出:

["a" "b" "c" "d" "e" "f" "g" "h" "i"]
Run Code Online (Sandbox Code Playgroud)

如果您希望它动态遍历所有字段,则可以使用该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
}
Run Code Online (Sandbox Code Playgroud)

使用它:

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

输出是一样的:

["a" "b" "c" "d" "e" "f" "g" "h" "i"]
Run Code Online (Sandbox Code Playgroud)

试试Go Playground上的例子。

使用更复杂的示例查看类似问题:

Golang,按字母顺序对结构字段进行排序

如何使用字段的 String() 打印结构?