Continuous time error when implementing index index

I have a structure that owns a HashMap<String, String> ,

 struct Test { data: HashMap<String, String>, } 

I am trying to implement the Index attribute for this type to match with the implementation of the hashmap Index (there is different logic, so I cannot expose the hash map).

This works if I just get a reference to the value in hashmap:

 impl<'b> Index<&'b str> for Test { type Output = String; fn index(&self, k: &'b str) -> &String { self.data.get(k).unwrap() } } 

However, I want to get &Option<&String> from it, for example data.get() . So I tried this:

 impl<'b, 'a> Index<&'b str> for Test { type Output = Option<&'a String>; fn index(&'a self, k: &'b str) -> &Option<&'a String> { &self.data.get(k) } } 

This leads to:

 error[E0207]: the lifetime parameter `'a` is not constrained by the impl trait, self type, or predicates --> <anon>:8:10 | 8 | impl<'b, 'a> Index<&'b str> for Test { | ^^ unconstrained lifetime parameter 

I understand the " unconstrained lifetime parameter in 'a ". Now 'a is the lifetime of Test , so I want (I think) where 'Self: 'a (so self lives at least as long as 'a ). I can't seem to figure this out for Index impl? I have tried some things with the addition of PhantomData to my Test . But I'm not going anywhere. Any suggestions?

+5
source share
1 answer

As noted in the comments, you won’t be able to do exactly what you want. But it seems to you that you really want to replicate the HashMap get method. Therefore, I suggest either writing your own or implementing Deref (and not DerefMut ) to provide the permanent owner of the structure with constant access directly to the internal HashMap . Hope this means the user cannot mess up your internal structure logic. Keep in mind that if you do both, then Deref will not be used to call HashMap::get , since Test::get will be available.

 struct FooMap { data: HashMap<String, String> } 

Replication get :

 impl FooMap { pub fn get(&self, index: &str) -> Option<&String> { self.data.get(index) } } 

Using Deref :

 impl Deref for FooMap { type Target = HashMap<String, String>; fn deref(&self) -> &Self::Target { &self.data } } 

Rust Playground Sample Code

+1
source

Source: https://habr.com/ru/post/1261750/


All Articles