Incerteza
Incerteza

Reputation: 34854

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

Is there a way to perform an index access to an instance of a struct like this:

struct MyStruct {
    // ...
}

impl MyStruct {
    // ...    
}

fn main() {
    let s = MyStruct::new();
    s["something"] = 533; // This is what I need
}

Upvotes: 9

Views: 6793

Answers (2)

huon
huon

Reputation: 101976

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

Upvotes: 17

Shepmaster
Shepmaster

Reputation: 430220

You want to use the Index trait (and its pair IndexMut):

use std::ops::Index;

#[derive(Copy, Clone)]
struct Foo;
struct Bar;

impl Index<Bar> for Foo {
    type Output = Foo;

    fn index<'a>(&'a self, _index: Bar) -> &'a Foo {
        println!("Indexing!");
        self
    }
}

fn main() {
    Foo[Bar];
}

Upvotes: 7

Related Questions