这些片段之间没有任何区别。他们生成完全相同的组件:
pub fn a(bytes: &[u8]) -> usize {
for (i, item) in bytes.iter().enumerate() {
if *item == b' ' {
return i;
}
}
0
}
pub fn b(bytes: &[u8]) -> usize {
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return i;
}
}
0
}
pub fn c(bytes: &[u8]) -> usize {
for (i, item) in bytes.iter().enumerate() {
if item == &b' ' {
return i;
}
}
0
}
playground::a:
negq %rsi
movq $-1, %rax
.LBB0_1:
leaq (%rsi,%rax), %rcx
cmpq $-1, %rcx
je .LBB0_2
cmpb $32, 1(%rdi,%rax)
leaq 1(%rax), %rax
jne .LBB0_1
retq
.LBB0_2:
xorl %eax, %eax
retq
; The code is identical so the functions are aliased
.set playground::b, playground::a
.set playground::c, playground::a
对于它的价值,我会把这个函数写成
pub fn a(bytes: &[u8]) -> Option<usize> {
bytes.iter().position(|&b| b == b' ')
}
iter()
[...]对在中找到的元素的引用bytes
Yes, iter
通常是一个返回引用迭代器的函数。
我需要比较
通常,您需要比较两个事物具有相同数量的参考文献 https://stackoverflow.com/q/52656800/155423或者有时存在一级参考差异。如何实现这一点并不重要——引用一个值或取消引用另一个值,或者通过*
作为表达式或通过&
在一个模式中。
也可以看看: