Skip to content

Instantly share code, notes, and snippets.

@chamakits
Forked from anonymous/playground.rs
Last active June 24, 2016 05:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chamakits/c40c05940c6e7fcf9e927d6b5928d7b2 to your computer and use it in GitHub Desktop.
Save chamakits/c40c05940c6e7fcf9e927d6b5928d7b2 to your computer and use it in GitHub Desktop.
Problemataic borrowing
struct NoLifetime {}
struct WithLifetime <'a> {
pub field: &'a i32
}
fn main() {
let mut some_val = NoLifetime{};
borrow_mut_function(&mut some_val);
borrow_mut_function(&mut some_val);//Borrowing as mutable for the second time.
let num = 5;
let mut life_val = WithLifetime{field:&num};
borrow_lifetime(&mut life_val);
borrow_lifetime(&mut life_val);//Borrowing as mutable for the second time.
let num_again = borrow_lifetime(&mut life_val); //Borrow, assign lifetime result
borrow_lifetime(&mut life_val);//Compiler: cannot borrow `life_val` as mutable more than
}
fn borrow_mut_function(val_in: &mut NoLifetime) -> String {
"abc".to_string()
}
fn borrow_lifetime<'a>(val_in: &'a mut WithLifetime) -> &'a i32 {
val_in.field
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment