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

怎甘沉沦 提交于 2020-01-09 11:59:08

问题


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
}

回答1:


You can use the Index and IndexMut traits.

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

struct Foo { x: i32, y: i32 }

impl<'a> Index<&'a str> for Foo {
    type Output = i32;
    fn index(&self, s: &&'a str) -> &i32 { // '
        match *s {
            "x" => &self.x,
            "y" => &self.y,
            _ => panic!("unknown field: {}", s)
        }
    }
}
impl<'a> IndexMut<&'a str> for Foo {
    type Output = i32;
    fn index_mut(&mut self, s: &&'a 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



回答2:


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];
}


来源:https://stackoverflow.com/questions/28126735/is-there-a-way-to-perform-an-index-access-to-an-instance-of-a-struct

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!