簡體   English   中英

Rust 中的 var 和 _var 有什么區別?

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

鑒於此:

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

Rust 編譯器產生這個警告:

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

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

打印以下內容( 操場):

dropping count 2
dropping count 1
dropping count 3
dropping count 1
dropping count 2
dropping count 3

_variablevariable之間的主要區別在於,第一個告訴編譯器如果我們不在代碼中使用它就不要發出任何警告。 例子:

// src/main.rs
fn main() {
    let _x = 1;
    let y = 2;
}

編譯main.rs給出:

warning: unused variable: `y`
 --> src/main.rs:3:9
  |
3 |     let y = 2;
  |         ^ help: if this is intentional, prefix it with an underscore: `_y`
  |
  = note: `#[warn(unused_variables)]` on by default

更有趣的情況是當我們將__variable進行比較時。

通過以 _ 開頭的名稱忽略未使用的變量

語法 _x 仍然將值綁定到變量,而 _ 根本不綁定。

考慮示例:

// src/main.rs
fn main() {
    let s = Some(String::from("Hello!"));

    if let Some(_s) = s {
        println!("found a string");
    }

    println!("{:?}", s);
}

當我們嘗試編譯main.rs我們得到錯誤:

error[E0382]: borrow of moved value: `s`
 --> src/main.rs:8:22
  |
4 |     if let Some(_s) = s {
  |                 -- value moved here
...
8 |     println!("{:?}", s);
  |                      ^ value borrowed here after partial move
  |
  = note: move occurs because value has type `std::string::String`, which does not implement the `Copy` trait
help: borrow this field in the pattern to avoid moving `s.0`
  |
4 |     if let Some(ref _s) = s {
  |                 ^^^

啊哈! 語法 _x 仍然將值綁定到變量,這意味着我們正在s的所有權轉移到_s ,因此,我們不能再訪問變量s了; 當我們嘗試打印s值時會發生這種情況。

正確的做法是:

// src/main.rs
fn main() {
    let s = Some(String::from("Hello!"));

    if let Some(_) = s {
        println!("found a string");
    }

    println!("{:?}", s);
}

上面的代碼工作得很好。 s不會被移動到_ ,所以我們以后仍然可以訪問它。

有時我將_與迭代器一起使用:

fn main() {
    let v = vec![1, 2, 3];
    let _ = v
        .iter()
        .map(|x| {
            println!("{}", x);
        })
        .collect::<Vec<_>>();
}

編譯給出結果:

1
2
3

當對上面的可迭代類型進行更復雜的操作時,上面的示例對我來說起到了實用程序的作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM