How to convert slice of structs to slice of strings in go?

二次信任 提交于 2019-12-14 03:58:07

问题


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.


回答1:


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?



来源:https://stackoverflow.com/questions/39968236/how-to-convert-slice-of-structs-to-slice-of-strings-in-go

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!