For loop on a structure's field names

If each “body” is some overall info about the body (height, weight, subject identity, etc…) and a list of segments, you could probably organize it as

struct Segment
    length::Float64
    mass::Float64
end
struct Body
    height::Float64
    segments::Vector{Segment}
end

and now body.segments[i] gives you the i-th segment. Note that you probably don’t need to make Segment mutable: you can just set the i-th element of the vector to a new Segment struct, without mutating the old one (it tends to be more efficient).

If body.segments[i] is a bit “unreadable” and you’d prefer to refer to the i-th segment by name (say arm or thigh) you can use (as suggested above) a data structure that is like an array, but also keeps a label, check out for example GitHub - SciML/LabelledArrays.jl: Arrays which also have a label for each element for easy scientific machine learning (SciML) (there are many alternatives, I personally haven’t really used any so can’t offer much advice here).

2 Likes