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

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

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.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题