Saya ingin menerapkan sifat Indeks untuk tipe pembungkus di atas tipe HashMap:

use std::collections::HashMap;
use std::option::Option;

#[cfg(test)]
use std::ops::Index;

#[derive(Debug, Clone)]
struct Value {
    val: i32,
}

#[derive(Debug, Clone)]
pub struct HMShadow {
    hashmap: HashMap<String, Value>,
}

impl HMShadow {
    fn new() -> HMShadow {
        HMShadow {
            hashmap: {
                HashMap::<String, Value>::new()
            },
        }
    }

    fn insert<S>(&mut self, key: S, element: Value) -> Option<Value>
        where S: Into<String>
    {
        self.hashmap.insert(key.into(), element)
    }

    fn get(&mut self, key: &str) -> &mut Value {
        self.hashmap.get_mut(key).expect("no entry found for key")
    }
}

fn main()
{
    let mut s: HMShadow = HMShadow::new();
    let v: Value = Value { val : 5 };
    let _ = s.insert("test", v);
    println!("{:?}", s);
    println!("Get: {}", s.get("test").val);
}

#[cfg(test)]
impl<'a> Index<&'a str> for HMShadow {
    type Output = &'a mut Value;

    fn index(&self, key: &'a str) -> &&'a mut Value {
        match self.hashmap.get_mut(key) {
            Some(val) => &mut val,
            _ => panic!("no entry found for key"),
        }
    }
}

#[cfg(test)]
#[test]
fn test_index() {
    let mut s: HMShadow = HMShadow::new();
    let v: Value = Value { val : 5 };
    let _ = s.insert("test", v);
    println!("{:?}", s);
    println!("Index: {}", s["test"].val);
}

Melakukan rustc --test tt.rs kompiler mengatakan:

error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements
  --> tt.rs:51:28
   |
51 |         match self.hashmap.get_mut(key) {
   |                            ^^^^^^^
   |
help: consider using an explicit lifetime parameter as shown: fn index(&'a self, key: &'a str) -> &&'a mut Value
  --> tt.rs:50:5
   |
50 |     fn index(&self, key: &'a str) -> &&'a mut Value {
   |     ^

Tapi saya tidak bisa melakukan fn index(&'a self, key: &'a str) -> &&'a mut Value karena sifat Indeks tidak mengizinkan &'a self dan kesalahan kompiler:

error[E0308]: metode tidak kompatibel dengan sifat

1
Harald Hoyer 13 Desember 2016, 13:29

1 menjawab

Saya kira, saya sedang mencari

#[cfg(test)]
impl<'a> IndexMut<&'a str> for HMShadow {
    fn index_mut<'b>(&'b mut self, key: &'a str) -> &'b mut Value {
        self.hashmap.get_mut(key).expect("no entry found for key")
    }
}
2
Harald Hoyer 13 Desember 2016, 12:18