RUST daily province: if let & while let

        When we use match, we must match completely. If you only need to judge a specific branch, then match will be redundant, and if let can only match a specific branch of interest. In this case, the writing method is simpler than match.

if let

        The syntax of if let is if let PATTERN=EXPRESSION{BODY}. Can be followed by an optional else branch.

use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
map.insert("one", 1);
map.insert("two", 2);

let value = if let Some(v) = map.get("one") {
v + 1
} else {
0
};

println!("{}", value);
}


        The if let block and while let block will also create a new scope, and value is of type Option<String>, so ownership will be transferred in the assignment operation of if let, and value will no longer be available. If the value is changed to Option<i32>, there is no problem, because i32 has copy semantics, which is what we call Copy, and you can verify it yourself.

fn main(){
    let value = Some(String::from("hello world"));
    if let Some(v) = value{
        println!("{:?}",v);
    }
    //println!("{:?}",value);
}

如果不注释println!("{:?}",value);则会报错

         If the pattern corresponding to the if let does not match successfully, then the code of the else branch will be executed. In addition, we can also mix if let, else if and else if let expressions for matching. This hybrid syntax can provide more flexibility, and the conditions in a series of if let, else if, else if let branches do not need to be related to each other.

fn main() {
let value1: Option<String> = None;
let value2 = false;
let value3: Result<i32> = Ok(20);

if let Some(value) = value1{
    println!("value1, {}", );
} else if value2 {
    println!("value2!");
} else if let Ok(value) = value3{
    if value> 30 {
        println!("value3 > 30");
    } else {
        println!("value3 < 30");
    }
} else {
        println!("end");
    }
}

while let

The construction of the conditional loop while let is very similar to if let, but it will repeatedly execute the same pattern match until it fails. Examples are as follows.

let a = Range(..);
while let Some(i) = a.next() {
// do something
}


 

Guess you like

Origin blog.csdn.net/xq723310/article/details/130261591
let