I\'m using the structs Foo
and Bar
from a library and I\'m getting a compilation error in the client code. I simplified the code to this:
You can limit the lifetime of the array
variable by placing it in a new scope with curly braces ({ ... }
):
fn main() {
let mut foo = Foo { some_str: "test" };
{
let mut array: [Bar; 1] = [foo.create_bar()];
process(&mut array);
}
foo.read_data();
}
You original code will work as-is once non-lexical lifetimes are enabled by default:
#![feature(nll)]
use std::marker::PhantomData;
struct Foo {
some_str: &'static str,
}
struct Bar<'a> {
some_str: &'static str,
marker: PhantomData<&'a Foo>,
}
impl Foo {
fn read_data(&self) {
// add code here
}
fn create_bar<'a>(&'a mut self) -> Bar<'a> {
Bar {
some_str: "test2",
marker: PhantomData,
}
}
}
fn process(_arr: &mut [Bar]) {}
fn main() {
let mut foo = Foo { some_str: "test" };
let mut array: [Bar; 1] = [foo.create_bar()];
process(&mut array);
foo.read_data();
}
With NLL, the borrow checker becomes more advanced and precise; it can now understand that you aren't using array
after the call to process
so it is safe to use foo
in a new manner.