Why this program getting error

fn main() {
 
	let mut x = "static str";
	let mut y = ok(&mut x);
	let z= &x;
}

fn ok<'s>(f :&'s mut &'s str){}

  1. i think ok function borrows x for complete program right..

its valid syntax right

Sorry, you're right. I misread your code.

Yes, you are mutably borrowing x for its entire lifetime (&'s mut &'s str), therefore it cannot be borrowed again.

If you want to fix it, elide the first lifetime (for the mutable borrow):

fn main() {
 
	let mut x = "static str";
	let mut y = ok(&mut x);
	let z= &x;
}

fn ok<'s>(f :&mut &'s str){}

This is because ok says that the lifetimes of the &mut … loan and the &str loan are the same — you've used the same lifetime variable for both.

The lifetime of a string literal is &'static, so when you have &'s mut &'static str and 's must equal the other lifetime, it's &'static mut &'static str.

&mut doesn't just mean it's mutable. It means it guarantees exclusive access to this reference for its entire lifetime. And &'static mut means it guarantees exclusive access forever. It means everything else is forbidden to borrow this value ever again, and this &'static mut can keep it for as long as it wants. So existence of &'staitc mut forbids possibility of &x used later, because &mut already promised there won't be another reference to its content.

This makes it work:

let mut y = ok(&mut &*x);

Because that changes &'static str to &'some_shorter_lifetime str and that can be paired with &'some_shorter_lifetime mut that doesn't promise to last forever.

5 Likes

Can u explain what is the meaning of 'a, 'static

These symbols name a scope in which a reference is guaranteed to be valid. 'static is a special case of an unlimited scope.

https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html

1 Like

Described in the document:
All string literals have the 'static lifetime, which we can annotate as follows:

let s: &'static str = "I have a static lifetime.";

so let mut x = "static str"; is the same as let mut x: &'static str = "static str";

One gotcha to look out for is that &mut and let mut are two very different features, unrelated to each other.

let mut just applies to the variable name, and it doesn't care exclusivity. It doesn't have lifetimes. It also doesn't allow you to mutate anything if you didn't already have permission to do so.

You must pay very close attention to &mut, but you can generally ignore existence of let mut and just add/remove the other mut when the compiler tells you to.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.