https://gcc.godbolt.org/z/jqEjasPTW中的
-C opt-level=3
编译的
#[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
}
}
产生这个汇编代码:
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
为什么在 match2 中将寄存器 edi 与 1 进行比较?
这里没有汇编专家,但我想这就是那里发生的事情(以伪代码形式):
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;
所以
edi
与1
的比较基本上是为了检查它是否是Some
。
当然 edi
和 esi
是函数参数,分别包含指示是否为 Some
的值和 Some
的值。