What's the difference between var and _var in Rust?

后端 未结 2 760
一整个雨季
一整个雨季 2021-01-21 18:05

Given this:

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

The Rust compiler produces this warning:



        
2条回答
  •  无人共我
    2021-01-21 18:34

    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
    

提交回复
热议问题