doulin6448 2019-08-10 21:45
浏览 46
已采纳

无需反射即可将结构转换为元组切片

I need to convert a struct into a []Tuple. Each tuple will represent a path to each leaf node of the struct. For example:

type inner struct {
  D int
}

type Example struct {
  A string
  B *inner
  C []inner
}

e := Example{
  A: "a",
  B: &inner{
    D: 0,
  },
  C: []inner{
    inner{D:0}, inner{D:1}, inner{D:2},
  },
}

func toTuple(e *Example) []Tuple {
  // this function should return:
  //  [
  //    Tuple{"A", "a"}
  //    Tuple{"B", "D", "0"}
  //    Tuple{"C", 0, "D", 0}
  //    Tuple{"C", 1, "D", 1}
  //    Tuple{"C", 2, "D", 2}
  //  ]
}

Is there any way to do this without having to manually specify each Tuple? I want to avoid having to do stuff like:

tuples = append(tuples, Tuple{"A", e.A})
...
...
for i, v := range e.C {
  tuples = append(tuples, Tuple{"C", i, "D", v.D}
}

because the struct could be quite large and that would lead to brittle, error prone code (for example if a new field is added to the struct).

As this is a performance sensitive application, I'd like to avoid the use of reflection. Is there any way to accomplish this?

  • 写回答

1条回答 默认 最新

  • dongyunshan4066 2019-09-03 02:29
    关注

    You're going to have to use reflection. I know reflection gets a bad rap performance-wise, but it's worth your time to try it and benchmark it before you write it off.

    Alternatively, you can use code generation - will probably still use reflection, but it would happen at codegen time to output go code that would be compiled together so the performance implication would not be at runtime.

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

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料