[Rust] Handle errors in Rust using expect()

This lesson discusses how to improve error handling by configuring custom error messages using the expect() function.

 
use std::io;

fn main() {
    let mut first = String::new();
    io::stdin().read_line(&mut first);
    
    // Not recommned to use uwnwrap()
    let a:u32 = first.trim().parse().unwrap()
    
    // Recommend to use expect() for better error handling
    let a:u32 = first.trim().parse().expect("This is a not a valid number")
}

 

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