use std::cell::{RefCell};
fn handle(_:&str) {
}
fn main() {
let foo = RefCell::new(Some("hello".to_owned()));
//Why does this work
handle(foo.borrow().as_ref().unwrap());
//but this doesn't?
let bar = foo.borrow().as_ref().unwrap();
handle(bar);
}
"temporary value is freed at the end of this statement"
This applies to any way you create temporary values. The opposite "temporary value created in argument exists until function call completes" is the basic rule that allows the first.
There is exact error message here: temporary value is freed at the end of this statement
You can do this:
let b = foo.borrow();
let bar = b.as_ref().unwrap();
and it works perfectly.
It is because calling foo.borrow() you got owned object of type Ref, and when you call as_ref on it, it just goes out of scope and is dropped - but there is borrow to it (returned by as_ref) which is illegal. What you need to do is to store Ref object somewhere, to prolong its lifetime till end of scope.