有没有办法对这样的结构实例执行索引访问:
struct MyStruct {
// ...
}
impl MyStruct {
// ...
}
fn main() {
let s = MyStruct::new();
s["something"] = 533; // This is what I need
}
答案 0 :(得分:7)
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"]);
}
打印:
x: 0
y: 2
答案 1 :(得分:3)
您想使用Index
trait(及其对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];
}