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?