相关疑难解决方法(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万
查看次数

对模式的引用匹配或取消引用的值之间有什么区别吗?

Clippy警告这样的代码:

fn func<T>(data: &Option<T>) {
    if let &Some(ref value) = data {}
}
Run Code Online (Sandbox Code Playgroud)
warning: you don't need to add `&` to all patterns
 --> src/main.rs:2:5
  |
2 |     if let &Some(ref value) = data {}
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: #[warn(match_ref_pats)] on by default
  = help: for further information visit https://rust-lang-nursery.github.io/rust-clippy/v0.0.210/index.html#match_ref_pats
help: instead of prefixing all patterns with `&`, you can dereference the expression
  |
2 |     if let Some(ref value) = *data {}
  |            ^^^^^^^^^^^^^^^   ^^^^^
Run Code Online (Sandbox Code Playgroud)

从编译器的角度来看,这些构造是否相同:

if …
Run Code Online (Sandbox Code Playgroud)

rust

2
推荐指数
1
解决办法
190
查看次数

标签 统计

rust ×2

dereference ×1

formal-semantics ×1

reference ×1