Why this code wont work

fn ok<'lt> (first:&'lt mut &'lt str,sec:char)->&'lt str{
" "
}

fn main(){
let mut x="sun";
let z= ok(&mut x,' ' );
println!("{}",x);
}

&'a mut T<'a> (where in this case T<'a> = &'a str) is almost always wrong, since it forces inner lifetime to be invariant - that is, to be unchangeable. Therefore, since x is &'static str, ok is called with 'static as generic parameter, and &mut x is essentially (in pseudocode) &'static mut x, which never expires and prohibits direct usage of x forever.

3 Likes

Recommend you read the book in my link as much as possible.

3 Likes

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.