This code compiled with
-C opt-level=3
in https://gcc.godbolt.org/z/jqEjasPTW
#[no_mangle]
pub fn match1(num: i32) -> i32 {
if num == 10 {99} else {11}
}
#[no_mangle]
pub fn match2(num: Option<i32>) -> i32 {
match num {
Some(a) => a,
_ => 11
}
}
produces this assembly code:
match1:
cmp edi, 10
mov ecx, 99
mov eax, 11
cmove eax, ecx
ret
match2:
cmp edi, 1
mov eax, 11
cmove eax, esi
ret
why in match2 compares the register edi with 1 ?
No assembly expert here but I guess this is what's happening there (in pseudo-code):
var eax = 11; // assume it's None
if (edi == 1) { // it's Some
eax = esi; // esi contains the "content" of Some, that is `a`
}
return eax;
So the comparison of edi
with 1
is basically done to check if it's Some
.
Of course edi
and esi
are the function parameters that contain, respectively, a value indicating if it's Some
and the value of Some
.