Rust 中的 var 和 _var 有什么区别? [英] What's the difference between var and _var in Rust?
问题描述
鉴于此:
fn main() {
let variable = [0; 15];
}
Rust 编译器产生这个警告:
The Rust compiler produces this warning:
= note: #[warn(unused_variables)] on by default
= note: to avoid this warning, consider using `_variable` instead
variable
和 _variable
有什么区别?
推荐答案
区别在于前面有一个下划线,这会导致 Rust 编译器允许它不被使用.它是裸下划线 _
的一种命名版本,可用于忽略值.
The difference is an underscore at the front, which causes the Rust compiler to allow it to be unused. It is kind of a named version of the bare underscore _
which can be used to ignore a value.
然而,_name
与 _
的行为不同.普通下划线立即删除值,而 _name
的作用与任何其他变量一样,并在作用域末尾删除值.
However, _name
acts differently than _
. The plain underscore drops the value immediately while _name
acts like any other variable and drops the value at the end of the scope.
它如何与普通下划线不完全相同的示例:
An example of how it does not act exactly the same as a plain underscore:
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
这篇关于Rust 中的 var 和 _var 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!