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条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效