Make borrow safe earlier

Consider the following code:

struct A<'a> { dal: &'a mut B, }
struct B { }

impl B {
	pub fn get_object(&mut self) -> Option<&str> { Some("Got Object") }
}

impl<'a> A<'a> {
	pub fn new(a: &mut B) -> A { A{ dal: a } }
	pub fn do_something(&mut self) {
		match self.dal.get_object() {
			None => {
				// this causes E0502 since *self.dal was a mutable borrowed and we are attempting to borrow *self.
				// In this case, *self is unusable, although it seems it would be perfectly safe to use... 
				// Shouldn't the borrow have ended when no valid reference was returned (like within Some(...))?
				self.report_error();
			},
			Some(v) => {
				println!("retreived {}", v);
			}
		}
	}

	fn report_error(&self) { println!("report some error..."); }
}

fn main() {
	let mut t = B{};
	let mut x = A::new(&mut t);

	x.do_something();
}

Shouldn’t it be made safe to borrow *self again after it’s previous use is no longer accessible?

Any thought?

I believe this is exactly the sort of code that will become legal with the “non-lexical lifetimes” feature, which is documented at https://github.com/rust-lang/rfcs/blob/master/text/2094-nll.md and is already implemented on nightly.

4 Likes

Yes, you can try it on nightly with #![feature(nll)] at the top of your crate, and this code is accepted.

6 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.