Rust programming video tutorial corresponding to explain the content – propagation error

Time:2021-6-13

Video address

Headline address:https://www.ixigua.com/i676544267458235648…
Station B address:https://www.bilibili.com/video/av78062009?…
Netease cloud classroom address:https://study.163.com/course/introduction….

Explanation content

1. When writing a function, but the function may fail, in addition to handling the error in the function, you can also pass the error to the caller, so that the caller can decide how to handle it. This is called propagation error.
example:

use std::io;
use std::io::Read;
use std::fs::File;
fn read_username_from_file() -> Result<String, io::Error> {
    let f = File::open("hello.txt");
    let mut f = match f {
        Ok(file) => file,
        Err(e) => return Err(e),
    };

    let mut s = String::new();
    match f.read_to_string(&mut s) {
        Ok(_) => Ok(s),
        Err(e) => Err(e),
    }
}

2. The abbreviated way of spreading mistakes and the advocated way

use std::io;
use std::io::Read;
use std::fs::File;

fn read_username_from_file() -> Result<String, io::Error> {
    let mut f = File::open("hello.txt")?;
    let mut s = String::new();
    f.read_to_string(&mut s)?;
    Ok(s)
}

3. Further abbreviation

use std::io;
use std::io::Read;
use std::fs::File;
fn read_username_from_file() -> Result<String, io::Error> {
    let mut s = String::new();
    File::open("hello.txt")?.read_to_string(&mut s)?;
    Ok(s)
}
//Note 1: Trust provides FS:: read_ to_ String function
use std::io;
use std::fs;
fn read_username_from_file() -> Result<String, io::Error> {
    fs::read_to_string("hello.txt")
}
//Note 2:? Operator is used to return a result function. If it is not a result function, use the? I'll report an error

3. When to use panic!, When to use result
(1) Examples, code prototypes and tests are suitable for panic, that is, direct panic Unwrap and expect
(2) The actual project should use more result

4. Option and result
Option is that there may be null values, and result is that there may be errors

This work adoptsCC agreementReprint must indicate the author and the link of this article

Linghu Yichong

Recommended Today

[database] MySQL exercises and answers (educational administration management system)_ MySQL_ 5.7)

✨ statement The answer to the exercise is not guaranteed to be completely correct, which is for reference only MySQL:5.7 Recommended software: Navicat premium Learning SQL statements requires diligent practice! ✨ Field description of each table course CId Course serial number, primary key PCId Prerequisite course DId Opening department number, foreign key CName Course name […]