[Rust] Handle errors in Rust using Pattern Matching

In this lesson we'll explore how to unwrap a Result type using a language feature called Pattern Matching.

 
use std::io;

fn main() {
    let mut first = String::new();
    io::stdin().read_line(&mut first).unwrap();
    
    let mut a:u32 = 0;
    
    match first.trim().parse() {
        Ok(val) => {
            a = val;
        },
        Err(err) => {
            println!("This is not a valid number")
        }
    }
}

 

posted @ 2024-02-23 14:33  Zhentiw  阅读(2)  评论(0编辑  收藏  举报