相关疑难解决方法(0)

什么是Rust的确切自动解除引用规则?

我正在学习/试验Rust,在我用这种语言找到的所有优雅中,有一个让我感到困惑并且看起来完全不合适的特点.

在进行方法调用时,Rust会自动取消引用指针.我做了一些测试来确定确切的行为:

struct X { val: i32 }
impl std::ops::Deref for X {
    type Target = i32;
    fn deref(&self) -> &i32 { &self.val }
}

trait M { fn m(self); }
impl M for i32   { fn m(self) { println!("i32::m()");  } }
impl M for X     { fn m(self) { println!("X::m()");    } }
impl M for &X    { fn m(self) { println!("&X::m()");   } }
impl M for &&X   { fn m(self) { println!("&&X::m()");  } }
impl M for &&&X  { …
Run Code Online (Sandbox Code Playgroud)

reference dereference formal-semantics rust

152
推荐指数
2
解决办法
2万
查看次数

为什么不能将借用的整数与文字整数进行比较?

我想在条件为真的数组中获取元素.例如.我想数组元素为0的所有索引:

fn main() {
    let lim = 10;
    let mut sieve = vec![0; lim + 1];
    sieve[1] = 1;
    println!(
        "{:?}",
        sieve
            .iter()
            .enumerate()
            .filter(|&(_, c)| c != 0)
            .map(|(i, _)| i)
            .collect::<Vec<usize>>()
    );
}
Run Code Online (Sandbox Code Playgroud)

但这是一个编译错误:

error[E0277]: can't compare `&{integer}` with `{integer}`
  --> src/main.rs:10:33
   |
10 |             .filter(|&(_, c)| c != 0)
   |                                 ^^ no implementation for `&{integer} == {integer}`
   |
   = help: the trait `std::cmp::PartialEq<{integer}>` is not implemented for `&{integer}`
Run Code Online (Sandbox Code Playgroud)

当我使用c.clone() != 0它工作.

如果我正确理解错误消息,Rust会抱怨它无法将借位与带整数的整数进行比较.我不明白为什么不应该这样.

reference rust

9
推荐指数
1
解决办法
3239
查看次数

标签 统计

reference ×2

rust ×2

dereference ×1

formal-semantics ×1