Rust 关于 let 语句中以下划线变量名需要注意的一个点, _, _var, var 三者在生命周期上的区别
-
以单纯的下划线
_
接收的变量会在当前语句结束后立即被 drop 掉(不会等到走出当前代码块) -
以下划线开头形如
_var
的变量,生命周期跟普通变量的生命周期规则一致
#[derive(Debug)]
struct Foo {
name: &'static str,
}
impl Foo {
fn new(name: &'static str) -> Self {
Self { name, }
}
}
impl Drop for Foo {
fn drop(&mut self) {
println!("drop: {:?}", self);
}
}
fn main() {
let d = Foo::new("d");
println!("{}", line!());
let _d = Foo::new("_d");
println!("{}", line!());
let _ = Foo::new("_"); // 这一句结束后立即 drop
println!("{}", line!());
println!("EOF");
}
输出
23
26
drop: Foo { name: "_" }
29
EOF
drop: Foo { name: "_d" }
drop: Foo { name: "d" }
- 然而例外就是 while let,if let,match 语句,它们在自己的作用域内一直持有临时变量,哪怕是像单个下划线
_
这种匿名变量
#[derive(Debug)]
struct Foo {
name: &'static str,
}
impl Foo {
fn new(name: &'static str) -> Self {
Self { name, }
}
}
impl Drop for Foo {
fn drop(&mut self) {
println!("drop: {:?}", self);
}
}
fn main() {
let d = Foo::new("d");
println!("{}", line!());
let _d = Foo::new("_d");
println!("{}", line!());
let _ = Foo::new("_"); // 这一句结束后立即 drop
println!("{}", line!());
while let _ = Foo::new("while"){
println!("in while"); // 在 while 代码块区间内一直持有 _ 变量
break;
}
if let _ = Some(Foo::new("if let")) {
println!("in if let"); // 在此 block 内一直持有 _ 变量
}
match Some(Foo::new("match")) {
Some(_) => {
println!("in match"); // 在此 block 内一直持有 _ 变量
},
None => {},
}
println!("EOF");
}
输出
22
25
drop: Foo { name: "_" }
28
in while
drop: Foo { name: "while" }
in if let
drop: Foo { name: "if let" }
in match
drop: Foo { name: "match" }
EOF
drop: Foo { name: "_d" }
drop: Foo { name: "d" }
+V why_null 请备注:from博客园