let mut a = 1;
let b = some_random_int_between_1_and_5;
a =
if b > 2 {
a
} else {
b
};
println!("a is the same: {}", a);
Depending on the value of b, the above code might not have any effect on a. Will the optimizer generate a non instruction in these cases or will it copy a to a?
pub fn foo(b: i32) -> i32 {
let mut a = 1;
a = if b > 2 {
a
} else {
b
};
a
}
generates the assembly
example::foo:
cmp edi, 2
mov eax, 1
cmovle eax, edi
ret
As you can see, it uses the cmovle instruction, which is short for "conditional move if less or equal", which either leaves a unchanged, or replaces it with b depending on the result of the comparison earlier in the assembly.
Since there is no branching in the resulting machine code, the answer to your question is that neither of the two options is the case.