鉴于这种:
fn main() {
let variable = [0; 15];
}
Run Code Online (Sandbox Code Playgroud)
Rust编译器生成此警告:
= note: #[warn(unused_variables)] on by default
= note: to avoid this warning, consider using `_variable` instead
Run Code Online (Sandbox Code Playgroud)
variable和之间有什么区别_variable?
区别在于前面的下划线,这导致Rust编译器允许它未被使用.它是裸下划线的命名版本,_可用于忽略值.
但是,_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);
}
}
Run Code Online (Sandbox Code Playgroud)
打印以下(游乐场):
dropping count 2
dropping count 1
dropping count 3
dropping count 1
dropping count 2
dropping count 3
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
389 次 |
| 最近记录: |