So, I have a pretty simple struct and method. The struct holds a vector, and the remove()
method just mimics the remove()
method from a hashmap. So, the user passes in a reference, a private method returns the key of that item, the item is removed, and the originally passed in item should be returned. But, I'm having a lifetimes issue.
Here is the code as it stands:
fn remove(&mut self, token: &Token) -> Option<&Token> {
let matched_key: Option<usize> = self.find_token_key(token.footprint());
match matched_key {
Some(key) => {
&self.signatures.remove(key);
Some(token)
},
None => None
}
}
That's pretty simple, but panics with
error[E0623]: lifetime mismatch
--> src/data/memory/mod.rs:61:13
|
56 | fn remove(&mut self, token: &Token) -> Option<&Token> {
I expected that. So, I added the explicit lifetimes so that the passed in token
and the returned token
have the same annotation.
fn remove<'a>(&mut self, token: &'a Token) -> Option<&'a Token> {
That panicked with an error I didn't expect. I've searched for a bit, but don't really understand what's happening.
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter 'a in generic type due to conflicting requirements
--> src/data/memory/mod.rs:56:1
|
56 | fn remove<'a>(&mut self, token: &'a Token) -> Option<&'a Token> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #2 defined on the method body at 56:1...
--> src/data/memory/mod.rs:56:1
|
56 | / fn remove<'a>(&mut self, token: &'a Token) -> Option<&'a Token> {
57 | | let matched_key: Option<usize> = self.find_token_key(token.footprint());
58 | | match matched_key {
59 | | Some(key) => {
... |
64 | | }
65 | | }
| |_^
note: ...but the lifetime must also be valid for the anonymous lifetime #1 defined on the method body at 56:1...
--> src/data/memory/mod.rs:56:1
|
56 | / fn remove<'a>(&mut self, token: &'a Token) -> Option<&'a Token> {
57 | | let matched_key: Option<usize> = self.find_token_key(token.footprint());
58 | | match matched_key {
59 | | Some(key) => {
... |
64 | | }
65 | | }
| |_^
= note: ...so that the method type is compatible with trait:
expected fn(&mut data::memory::MemoryRepository, &tokens::token::Token) -> std::option::Option<&tokens::token::Token>
found fn(&mut data::memory::MemoryRepository, &tokens::token::Token) -> std::option::Option<&tokens::token::Token>
error: aborting due to previous error
I've tried various combinations with no luck. What am I doing wrong?