Here is the code in question:
struct CodeGenerator;
struct Command<'a> {
command: &'a String,
}
struct Expression;
impl CodeGenerator {
fn compile_push_arguments<'a>(
&'a mut self,
arguments: &'a Vec<Expression>,
) -> Vec<Command<'a>> {
arguments
.into_iter()
.flat_map(|argument| self.compile_expression(argument))
.collect()
}
fn compile_expression<'a>(&'a mut self, expression: &'a Expression) -> Vec<Command<'a>> {
todo!()
}
}
This produces the following compile error:
error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements
--> src/main.rs:14:39
|
14 | .flat_map(|argument| self.compile_expression(argument))
| ^^^^^^^^^^^^^^^^^^
|
note: first, the lifetime cannot outlive the lifetime `'_` as defined here...
--> src/main.rs:14:23
|
14 | .flat_map(|argument| self.compile_expression(argument))
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
note: ...so that closure can access `self`
--> src/main.rs:14:34
|
14 | .flat_map(|argument| self.compile_expression(argument))
| ^^^^
note: but, the lifetime must be valid for the lifetime `'a` as defined here...
--> src/main.rs:8:31
|
8 | fn compile_push_arguments<'a>(
| ^^
note: ...so that the types are compatible
--> src/main.rs:12:9
|
12 | / arguments
13 | | .into_iter()
14 | | .flat_map(|argument| self.compile_expression(argument))
15 | | .collect()
| |______________________^
= note: expected `Vec<Command<'a>>`
found `Vec<Command<'_>>`
For more information about this error, try `rustc --explain E0495`.
There are a number of things I don't understand in this error message:
- Where is the "autoref" happening here?
- Which lifetime is being referred to when it says "first, the lifetime cannot outlive the lifetime
'_
as defined here..."? Does the closure implicitly create a lifetime for itself? - Where it says "so that the types are compatible" - In what way exactly are the types not currently compatible?
Basically, I want to understand the error.
I noticed that removing the mut
from the reference to self fixes it, but I'm not sure why.