Any way to get details from a struct

struct Demo{
    f1:&'static str,
    f2:i32
}

Qustions:

  1. how to list all fields from a struct?
  2. how to set a struct attribute value with string field name?

Demo example:

let mut d=Demo{f1:"abc",f2:1};
// just demo
d["f1"] = "efg";
// or
d("f2") ="efg";

Rust doesn't have reflection, as such. It has some limited facilities (through std::any::Any) for inspecting the type of a value, but no runtime facilities for inspecting the structure of a type in a general way.

Common approaches to genericity in Rust include:

  • Generics, unsurprisingly. A trait that can store/retrieve values by name and type isn't terribly hard to design and implement.
  • Macros.
  • Procedural macros/custom derives.

All of these approaches address the problem at compile time, not at runtime.

What's the problem to which "Access fields by name at runtime" is the solution?

3 Likes

Agree with @derspiny but to add; the typical (dependent on problem) runtime solution is not to use a new struct but instead use a HashMap.

1 Like

thx