I'm trying to implement custom control structures in Rust. For example, suppose that for whatever reason, I want to implement a custom if
statement as a function. The function would take a condition, a closure representing the true branch and a closure representing the false branch. Depending on the condition, I would call the true branch closure or the false branch closure.
It looks something like this:
pub fn fun_if<O>(
cond: bool,
mut tbranch: impl FnMut() -> O,
mut fbranch: impl FnMut() -> O,
) -> O {
if cond {
tbranch()
} else {
fbranch()
}
}
The problem with this implementation is that the true closure can not mutably borrow the same variables as the false closure:
let mut test = 0;
fun_if(true, || test = 1, || test = 2)
^^^^ ^^^^ ! error !
However, the rust if
statement is smart enough to know that the true and false branch will never be called together. The following compiles just fine:
let mut test = 0;
if true {
test = 1
} else {
test = 2
}
My question is if the behavior of if is possible to replicate with functions and unsafe code in rust.
(This is a slightly contrived example and I'm happy to provide the real example where this came up if anybody is interested. What I asked here is the core idea though.)