Skip to content

Instantly share code, notes, and snippets.

@theevocater
Last active August 29, 2015 14:06
Show Gist options
  • Save theevocater/888f16daa20004de38d4 to your computer and use it in GitHub Desktop.
Save theevocater/888f16daa20004de38d4 to your computer and use it in GitHub Desktop.
I was messing around with closures and ran into an odd problem with lifetimes and borrowing.
// these two I just don't understand why neither works.
fn it_does_not_works() -> String {
let mut output_string = String::new();
let do_a_thing: || -> () = | | {
output_string;
};
do_a_thing();
return output_string;
}
// I assume this should compile like the example that follows it, but *shrug*
fn it_also_does_not_works() -> String {
let mut output_string = String::new();
{
let do_a_thing: || -> () = | | {
output_string;
};
do_a_thing();
}
return output_string;
}
// this compiles as expected
fn it_works() -> String {
let mut output_string = String::new();
{
let do_a_thing: || -> () = | | {
output_string.push_char('a');
};
do_a_thing();
}
return output_string;
}
// it seems like this should work if the above does. I specified a slightly
// shorter lifetime in the above example, but the closure's lifetime ends
// here at the function here. I think this is a corner case where the return
// happens to the borrow checker before it realizes the closure would be out
// of scope.
fn this_does_not_works() -> String {
let mut output_string = String::new();
let do_a_thing: || -> () = | | {
output_string.push_char('a');
};
do_a_thing();
return output_string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment