I've been trying to create a simple interpreter in Rust. Here's a code snippet.
use std::vec::Vec;
use std::option::Option;
use std::borrow::Borrow;
trait Data {}
trait Instruction {
fn run(&self, stack: &mut Vec<Box<Data>>) -> Option<&Data>;
}
struct Get {
stack_index: usize,
}
impl Instruction for Get {
fn run(&self, stack: &mut Vec<Box<Data>>) -> Option<&Data> {
Some(stack[self.stack_index].borrow())
}
}
fn main() {}
The above contains a simple Get
instruction. It has a run
method which simply returns a value from the given stack of Data
. Data
is an abstract trait representing really any type of data. I haven't implemented Data
yet.
However compiling the code generates error code E0495
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements
--> <anon>:17:14
|
17 | Some(stack[self.stack_index].borrow())
| ^^^^^^^^^^^^^^^^^^^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #2 defined on the body at 16:63...
--> <anon>:16:64
|
16 | fn run(&self, stack: &mut Vec<Box<Data>>) -> Option<&Data> {
| ________________________________________________________________^ starting here...
17 | | Some(stack[self.stack_index].borrow())
18 | | }
| |_____^ ...ending here
note: ...so that reference does not outlive borrowed content
--> <anon>:17:14
|
17 | Some(stack[self.stack_index].borrow())
| ^^^^^
note: but, the lifetime must be valid for the anonymous lifetime #1 defined on the body at 16:63...
--> <anon>:16:64
|
16 | fn run(&self, stack: &mut Vec<Box<Data>>) -> Option<&Data> {
| ________________________________________________________________^ starting here...
17 | | Some(stack[self.stack_index].borrow())
18 | | }
| |_____^ ...ending here
note: ...so that expression is assignable (expected std::option::Option<&Data>, found std::option::Option<&Data>)
--> <anon>:17:9
|
17 | Some(stack[self.stack_index].borrow())
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
What am I missing?