duandongji2231 2017-01-18 16:30
浏览 32
已采纳

在golang中遍历结构而不反射

I have a struct like this

import (
        "fmt"
)

type Node struct {
        m []string
        o []string
}

func main() {

        var mm = []string{"abc", "def"}
        var oo = []string{"111", "222"}

        var v = Node{m: mm, o: oo}

        for _, d := range []interface{}{v.m, v.o} {
                fmt.Println(d)
        }

}

The output I get is,

[abc def]
[111 222]

My desired output is,

abc,111
def,222

I don't want to use reflect package because, I want to use native go built-ins as much as possible. If it becomes too burdensome I will fall back on reflect package.

  • 写回答

3条回答 默认 最新

  • douhui3305 2017-01-19 08:43
    关注

    Edit: I just realized my output doesn't match yours, do you want the letters paired with the numbers? If so then you'll need to re-work what you have.

    You can use strings.Join and a type switch statement to accomplish this:

    https://play.golang.org/p/ygtdxv02uK

    package main
    
    import (
        "fmt"
        "strings"
    )
    
    type Node struct {
        m []string
        o []string
        p []int
    }
    
    func main() {
    
        var mm = []string{"abc", "def"}
        var oo = []string{"111", "222"}
        var pp = []int{1, 2, 3}
    
        var v = Node{m: mm, o: oo, p: pp}
    
        for _, d := range []interface{}{v.m, v.o, v.p} {
            switch d.(type) {
            case []string:
                fmt.Println(strings.Join(d.([]string), ","))
            default:
                fmt.Println(d)
            }
        }
    
    }
    

    The output is:

    abc,def
    111,222
    [1 2 3]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式