Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
656 views
in Technique[技术] by (71.8m points)

rust - 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
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...