Rust 编程视频教程对应讲解内容-错误

视频地址

头条地址:https://www.ixigua.com/i6765442674582356483
B站地址:https://www.bilibili.com/video/av78062009?p=1
网易云课堂地址:https://study.163.com/course/introduction.htm?courseId=1209596906#/courseDetail?tab=1

讲解内容

1、rust语言将错误分为两个类别:可恢复错误和不可恢复错误
(1)可恢复错误通常代表向用户报告错误和重试操作是合理的情况,例如未找到文件。rust中使用Result来实现。
(2)不可恢复错误是bug的同义词,如尝试访问超过数组结尾的位置。rust中通过panic!来实现。

2、panic!

fn main() {
    panic!("crash and burn");
}

3、使用BACKTRACE
例子:

fn main() {
    let v = vec![1, 2, 3];
    v[99];
}

运行时:RUST_BACKTRACE=1(任何不为0的值即可) cargo run,会打印出完整的堆栈。

4、Result
原型:

enum Result {
    Ok(T),
    Err(E),
}

使用例子:

use std::fs::File;
fn main() {
    let f = File::open("hello.txt");
    let f = match f {
        Ok(file) => file,
        Err(error) => {
            panic!("Problem opening the file: {:?}", error)
        },
    };
}

使用match匹配不同的错误:

use std::fs::File;
fn main() {
    let f = File::open("hello.txt");
    let f = match f {
        Ok(file) => file,
        Err(error) => match error.kind() {
            ErrorKing::NotFound => println!("Not found!"),
            _ =>panic!("Problem opening the file: {:?}", error),
        },
    };
}

5、失败时的简写
(1)unwrap
例子:

use std::fs::File;
fn main() {
    let f = File::open("hello.txt").unwrap();
}

(2)expect
例子:

use std::fs::File;
fn main() {
    let f = File::open("hello.txt").expect("Failed to open hello.txt");
}

你可能感兴趣的:(Rust 编程视频教程对应讲解内容-错误)