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?