考虑以下情况:
fn main() {
let variable = [0; 15];
}
Rust编译器会产生这个警告:
= note: #[warn(unused_variables)] on by default
= note: to avoid this warning, consider using `_variable` instead
“variable”和“_variable”有什么区别?
考虑以下情况:
fn main() {
let variable = [0; 15];
}
Rust编译器会产生这个警告:
= note: #[warn(unused_variables)] on by default
= note: to avoid this warning, consider using `_variable` instead
_
的命名版本,可以用来忽略值。_name
与_
的作用不同。普通下划线会立即丢弃值,而_name
则像任何其他变量一样,在作用域结束时丢弃值。struct Count(i32);
impl Drop for Count {
fn drop(&mut self) {
println!("dropping count {}", self.0);
}
}
fn main() {
{
let _a = Count(3);
let _ = Count(2);
let _c = Count(1);
}
{
let _a = Count(3);
let _b = Count(2);
let _c = Count(1);
}
}
打印以下内容 (playground):
dropping count 2
dropping count 1
dropping count 3
dropping count 1
dropping count 2
dropping count 3
_variable
和 variable
之间的关键区别在于,第一个告诉编译器如果我们在代码中不使用它,则不要发出任何警告。例如:
// src/main.rs
fn main() {
let _x = 1;
let y = 2;
}
main.rs
的结果如下:warning: unused variable: `y`
--> src/main.rs:3:9
|
3 | let y = 2;
| ^ help: if this is intentional, prefix it with an underscore: `_y`
|
= note: `#[warn(unused_variables)]` on by default
_
和_variable
时。
语法
_x
仍将值绑定到变量,而_
根本不绑定。
考虑以下示例:
// src/main.rs
fn main() {
let s = Some(String::from("Hello!"));
if let Some(_s) = s {
println!("found a string");
}
println!("{:?}", s);
}
当我们尝试编译main.rs
时,会出现错误:
error[E0382]: borrow of moved value: `s`
--> src/main.rs:8:22
|
4 | if let Some(_s) = s {
| -- value moved here
...
8 | println!("{:?}", s);
| ^ value borrowed here after partial move
|
= note: move occurs because value has type `std::string::String`, which does not implement the `Copy` trait
help: borrow this field in the pattern to avoid moving `s.0`
|
4 | if let Some(ref _s) = s {
| ^^^
s
的所有权转移到_s
,因此,我们无法再访问变量s
;当我们尝试打印s
的值时,就会发生这种情况。// src/main.rs
fn main() {
let s = Some(String::from("Hello!"));
if let Some(_) = s {
println!("found a string");
}
println!("{:?}", s);
}
s
没有被移动到_
中,所以我们仍然可以在后面访问它。_
:fn main() {
let v = vec![1, 2, 3];
let _ = v
.iter()
.map(|x| {
println!("{}", x);
})
.collect::<Vec<_>>();
}
1
2
3
当我在可迭代类型上进行更复杂的操作时,上面的例子对我来说就像一个实用工具。
let _x = y;
会_移动_y
,因此该语句之后y
不再有效,而let _ = y;
不会移动y
。 - Sven Marnach