Rust programming video tutorial (Advanced) – 027_ 2 advanced features 2

Time:2021-9-21

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. Never return never type
Rust has one called! Special types of. In the terminology of type theory, it is called empty type because it has no value. We prefer to call it never type. Serve as the return value when the function does not return:

fn bar() -> ! { 
    // --snip--
}

Example 1:
//Cargo.toml file

[dependencies] rand = "0.6.0"

//src/main.rs

use std::io; 
use std::cmp::Ordering; 
use rand::Rng; 
fn main() { 
    println!("Guess the number!"); 
    let secret_number = rand::thread_rng().gen_range(1, 101);
    loop { 
        println!("Please input your guess."); 
        let mut guess = String::new(); 
        io::stdin().read_line(&mut guess) .expect("Failed to read line"); 
        let guess: u32 = match guess.trim().parse() { 
            Ok(num) => num, 
            Err (;) = > continue, // the value of continue is!.
            //When rust wants to calculate the type of guess, it looks at the two branches.
            //The former is the U32 value, while the latter is! Value.
            //Because! With theout a value, rust decides that guess is of the type U32
            };         

        println!("You guessed: {}", guess); 
        match guess.cmp(&secret_number) { 
            Ordering::Less => println!("Too small!"), 
            Ordering::Greater => println!("Too big!"), 
            Ordering::Equal => { 
                println!("You win!"); 
                break; 
            } 
        } 
    } 
}

Note: never type can be forcibly converted to any other type. The reason why match branches are allowed to end with continue is that continue does not really return a value; On the contrary, it returns control to the upper loop, so in the case of err, guess is not actually assigned.

Example 2: panic!
Unwrap function code on option:

impl<T> Option<T> { 
    pub fn unwrap(self) -> T { 
        match self { 
            Some(val) => val, 
            None => panic!("called `Option::unwrap()` on a `None` value"),
        } 
    }
}

explain:
During match, rust knows that Val is type T, panic! Yes! Type, so the result of the whole match expression is type T.

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

Linghu rushed