What's the difference between var and _var in

2019-07-14 04:31发布

Given this:

fn main() {
   let variable = [0; 15];
}

The Rust compiler produces this warning:

= note: #[warn(unused_variables)] on by default
= note: to avoid this warning, consider using `_variable` instead

What's the difference between variable and _variable?

标签: rust
1条回答
ゆ 、 Hurt°
2楼-- · 2019-07-14 05:12

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.

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);
    }
}

prints the following (playground):

dropping count 2
dropping count 1
dropping count 3
dropping count 1
dropping count 2
dropping count 3
查看更多
登录 后发表回答