Rust 中的 var 和 _var 有什么区别? [英] What's the difference between var and _var in Rust?

查看:69
本文介绍了Rust 中的 var 和 _var 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于此:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆