Is there a way to perform an index access to an instance of a struct?

You can use the Index and IndexMut traits.

use std::ops::{Index, IndexMut};

struct Foo {
    x: i32,
    y: i32,
}

impl Index<&'_ str> for Foo {
    type Output = i32;
    fn index(&self, s: &str) -> &i32 {
        match s {
            "x" => &self.x,
            "y" => &self.y,
            _ => panic!("unknown field: {}", s),
        }
    }
}

impl IndexMut<&'_ str> for Foo {
    fn index_mut(&mut self, s: &str) -> &mut i32 {
        match s {
            "x" => &mut self.x,
            "y" => &mut self.y,
            _ => panic!("unknown field: {}", s),
        }
    }
}

fn main() {
    let mut foo = Foo { x: 0, y: 0 };

    foo["y"] += 2;
    println!("x: {}", foo["x"]);
    println!("y: {}", foo["y"]);
}

It prints:

x: 0
y: 2

Leave a Comment