繁体   English   中英

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

[英]How to convert slice of structs to slice of strings in go?

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

type TagRow struct {
    Tag1 string  
    Tag2 string  
    Tag3 string  
}

其中 yields 切片如下:

[{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)

所以感谢你的帮助。

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

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,按字母顺序对结构字段进行排序

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM