[英]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
_variable
和variable
之間的主要區別在於,第一個告訴編譯器如果我們不在代碼中使用它就不要發出任何警告。 例子:
// 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.