I'm new to Rust, probably missing something obvious. I have the following code with the main idea of being able to index any struct field like so struct_instance['field'].
use std::ops::Index;
enum Selection {
Full,
Partial,
}
struct Config {
display: bool,
timeout: u16,
selection: Selection,
}
impl Index<&'_ str> for Config {
type Output = bool;
fn index(&self, index: &'_ str) -> &Self::Output {
match index {
"display" => &self.display,
_ => panic!("Unknown field: {}", index),
}
}
}
fn main() {
let config = Config {
display: true,
timeout: 500,
selection: Selection::Partial,
};
let display = config["display"];
println!("{display}");
}
The problem is: I can not find a way to index every type of struct fields, because associated type Output doesn't let me define more than one type. I would want to have match being able to process all Config fields somehow, is there a way to do so?
config.display?&strfor both writing to file and accessing struct value.Indextrait is mainly intended for arrays-like structures and doesn't really apply here. I would suggest not trying to use it andmatching the string directly. It's difficult to give a more detailed answer without seeing code, so please include a reproducible example.Box<dyn Field>whereFieldmust be implemented for each field of your struct. Not really useful I think tho. (Or aenumwith all possible types)