我正在学习/试验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) 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)