【问题标题】:What are the differences between using * and & to compare values for equality?使用 * 和 & 比较值是否相等有什么区别?
【发布时间】:2018-10-06 18:32:28
【问题描述】:

我想我理解,Rust 中&* 之间的区别在很大程度上与内存管理有关。

下面的代码sn-ps有什么区别。采用一种方法与另一种方法相比是否存在危险?

for (i, item) in bytes.iter().enumerate() {
    if *item == b' ' {
        return i;
    }
}
for (i, &item) in bytes.iter().enumerate() {
    if item == b' ' {
        return i;
    }
}
for (i, item) in bytes.iter().enumerate() {
    if item == &b' ' {
        return i;
    }
}

据我了解,当我从iter() 返回一个值时,我返回的是对bytes 中的元素的引用。如果我想对项目进行比较,我需要在两个引用 &u8 之间进行比较,或者我需要让 &item 本身成为一个引用,这样当我调用 item 时它的类型是 u8,或者当我比较它时,我需要取消引用item,以便item = &u8 -> *item = u8

  1. 当我使用(i, &item) 运行代码时,当我稍后调用item 时,这是否与第二个示例中的取消引用完全相同,或者编译器如何解释存在根本差异第一个代码sn-p和第二个代码sn-p?

  2. 第三个代码sn-p有什么问题吗?我意识到这是一个基于意见的问题。我意识到,如果我要使用item(或*item,或将值分配为引用)为另一个变量分配一个值,我稍后会返回不同的数据类型。除了管理您的数据类型之外,在考虑 item == &b' ' 是否适合这项工作时,还有什么需要注意的吗?

【问题讨论】:

    标签: rust


    【解决方案1】:

    这些 sn-ps 之间没有任何区别。它们生成完全相同的程序集

    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 中的元素的引用

    是的,iter 通常是一个返回引用迭代器的函数。

    我需要比较

    一般情况下,您需要在两个事物之间进行比较with the same amount of references 或者有时是一级参考差异。如何实现这一点并不重要——引用一个值或取消引用另一个值,或者通过* 作为表达式或通过&amp; 在模式中取消引用。

    另见:

    【讨论】:

    • 更容易使用bytes.iter().position(|&amp;b| b == b' ').
    • @SvenMarnach 好点!我只是去了链式表格并停在那里;-)
    猜你喜欢
    • 2018-09-12
    • 1970-01-01
    • 2011-06-11
    • 2016-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多