dongna2498 2016-10-10 23:25
浏览 82
已采纳

如何在Go中将结构片段转换为字符串片段?

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条回答 默认 最新

  • drake900918 2016-10-10 23:36
    关注

    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
    ", 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
    ", 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?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名