Rust programming video tutorial (Advanced) – 024_ 3 syntax of all modes 3

Time:2021-9-17

Video address

Headline address:https://www.ixigua.com/i677586170644791348…
Station B address:https://www.bilibili.com/video/av81202308/

Source address

GitHub address:https://github.com/anonymousGiga/learn_rus…

Explanation content

1. Ignore values in mode
(1) Use_ Ignore entire value
example:

fn foo(_: i32, y: i32) {
    println!("This code only uses the y parameter: {}", y);
}
fn main() {
    foo(3, 4);
}

Note: placeholders are used for parameters in the function, mainly when implementing trait (for example, it is not necessary to specify a parameter in the function).

(2) Use_ Ignore partial values

let numbers = (2, 4, 8, 16, 32);
match numbers {
    (first, _, third, _, fifth) => {
        println!("Some numbers: {}, {}, {}", first, third, fifth)
    },
}

(3) Ignore unused variables by beginning the name with an underscore
Example 1:

fn main() {
    let _x = 5;
    let y = 10;
}

Note: in the above code, the unused y will be warned during compilation, and the unused x will not be warned.

Use only_ There are some subtle differences from names that start with an underscore: for example_ X still binds the value to the variable, and_ Will not bind at all.

Example 2:

//An error will be reported because variables starting with an underscore will still bind values
let s = Some(String::from("Hello!"));
if let Some(_s) = s {
    println!("found a string");
}
println!("{:?}", s);

Example 3:

//No error will be reported because the ownership of s will not be moved to\_ in
let s = Some(String::from("Hello!"));
if let Some(_) = s {
    println!("found a string");
}
println!("{:?}", s);

(4) Ignore remaining values with
For values with multiple parts, you can use the.. syntax to use only parts and ignore other values
Example 1:

fn main() {
    let numbers = (2, 4, 8, 16, 32);
    match numbers {
        (first,.., last) = > {// automatically match to the first and last values
            println!("Some numbers: {}, {}", first, last);
        },
    }
}

Example 2:

//The following example is wrong because... Matching must be unambiguous
fn main() {
    let numbers = (2, 4, 8, 16, 32);
    match numbers {
        (.., second, ..) => {
            println!("Some numbers: {}", second)
        },
    }
}

This work adoptsCC agreement, reprint must indicate the author and the link to this article

Linghu rushed

Recommended Today

Seven Python code review tools recommended

althoughPythonLanguage is one of the most flexible development languages at present, but developers often abuse its flexibility and even violate relevant standards. So PythoncodeThe following common quality problems often occur: Some unused modules have been imported Function is missing arguments in various calls The appropriate format indentation is missing Missing appropriate spaces before and after […]