You can do this by creating and then immediately invoking a closure:
pub fn some_method(&mut self)
{
let x = yamama();
let result = (|| {
// do other stuff here
})();
println!("{}, {}", self.something, x);
result
}
That way, any use of ?
or return
within the closure will only leave that closure, and the println will still be executed. This avoids the need to rebind self
to another variable.
If you don't like that the cleanup code is written after the main body rather than before it, you could write a macro to flip the order:
macro_rules! cleanup {
($cleanup:block, $main:block) => {
let result = || $main;
$cleanup;
result
}
}
cleanup!({ println!("{} {}", self.something, x); }, {
// do other stuff here
});
On nightly there's also the option of using try
blocks, but those are probably worse for your use case, since they only affect where ?
jumps to, not return
.