Why does a match
on an inline value not act identically to declaring that value as a variable, when the cope of the arms is concerned?
let d = a.b().c();
match d {}
vs
match a.b().c() {}
I would expect there to be no difference in scope for the arms
Full example
Consider something like the below code. This runs without panic just fine, as would be expected.
use std::cell::RefCell;
use std::rc::Rc;
struct Node {
regen_at: Option<u32>,
energy: u32,
max_energy: u32,
}
fn schedule(regen_at: u32, task: impl 'static + FnMut()) {
// Save the task...
}
fn schedule_refresh(rc: Rc<RefCell<Node>>) {
let regen_at = 300;
rc.borrow_mut().regen_at = Some(regen_at);
schedule(regen_at, move || {
let mut cn = rc.borrow_mut();
cn.energy = cn.max_energy;
});
}
fn check_refresh(rc: Rc<RefCell<Node>>) {
let regen_at = rc.borrow().regen_at;
match regen_at {
Some(_) => (),
None => schedule_refresh(rc.clone()),
};
}
fn main() {
let node = Rc::new(RefCell::new(Node { regen_at: None, energy: 50, max_energy: 100 }));
check_refresh(node.clone());
let n = node.borrow();
println!("{:?}, {}, {}", n.regen_at, n.energy, n.max_energy);
}
However, if we change that match
in check_refresh
to put the variable in-line, this panics when that RefCell
is borrow_mut
'd in schedule_refresh
.
EDIT: I guess assignment does this too.
rc.borrow_mut().energy = rc.borrow().max_energy;
panics, even though the right side should be able to fully resolve before the left side.
There has to be a reason for this, I'm just curious what it is.