Search code examples
rust

Access struct field by variable


I want to iterate over over the fields of a struct and access its respective value for each iteration:

#[derive(Default, Debug)]
struct A {
    foo: String,
    bar: String,
    baz: String
}


fn main() {
    let fields = vec!["foo", "bar", "baz"];
    let a: A = Default::default();

    for field in fields {
        let value = a[field] // this doesn't work
    }
}

How can I access a field by variable?


Solution

  • Rust doesn't have any way of iterating directly over its fields. You should instead use a collection type such as Vec, array or one of the collections in std::collections if your data semantically represents a collection of some sort.

    If you still feel the need to iterate over the fields, perhaps you need to re-consider your approach to your task and see if there isn't a more idiomatic/proper way to accomplish it