克里皮对这样的代码发出警告:
fn func<T>(data: &Option<T>) {
if let &Some(ref value) = data {}
}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 {}
| ^^^^^^^^^^^^^^^ ^^^^^从编译器的角度来看,这些构造是否相同:
if let &Some(ref value) = data {if let Some(ref value) = *data {如果是这样的话,那么使用统一风格的克里皮消息有什么意义呢?
发布于 2017-04-12 13:01:50
是的,这对编译器来说是一样的。在这种情况下,没有什么好处。真正的好处来自于match等价物:
fn func(data: &Foo) {
match data {
&Foo::One => {}
&Foo::Two => {}
&Foo::Three => {}
}
}在这里,您只需要在模式中放置一个取消引用,而不是3个引用:
fn func(data: &Foo) {
match *data {
Foo::One => {}
Foo::Two => {}
Foo::Three => {}
}
}从Rust 1.26开始,您甚至不必取消匹配表达式的引用:
fn func(data: &Foo) {
match data {
Foo::One => {}
Foo::Two => {}
Foo::Three => {}
}
}这就是为什么这是惯用的选择。
if let概念只是对此的一个扩展。
你不能总是放弃这个价值。如果您试图对一对项目执行相同的操作:
fn func(data: &Foo, data2: &Foo) {
match (*data, *data2) {
(Foo::One, _) => {}
(Foo::Two, _) => {}
(Foo::Three, _) => {}
}
}你得到了错误
error[E0507]: cannot move out of borrowed content
--> src/main.rs:8:12
|
8 | match (*data, *data2) {
| ^^^^^ cannot move out of borrowed content在这种情况下,您可以使用参考表格:
fn func(data: &Foo, data2: &Foo) {
match (data, data2) {
(&Foo::One, _) => {}
(&Foo::Two, _) => {}
(&Foo::Three, _) => {}
}
}或者,从Rust 1.26开始,执行一些隐式引用:
fn func(data: &Foo, data2: &Foo) {
match (data, data2) {
(Foo::One, x) => {}
(Foo::Two, _) => {}
(Foo::Three, _) => {}
}
}https://stackoverflow.com/questions/43370054
复制相似问题