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

视频地址

头条地址:https://www.ixigua.com/i676544267458235648...
B站地址:https://www.bilibili.com/video/av78062009?...
网易云课堂地址:https://study.163.com/course/introduction....

讲解内容

1、rust语言将错误分为两个类别:可恢复错误和不可恢复错误
(1)可恢复错误通常代表向用户报告错误和重试操作是合理的情况,例如未找到文件。rust中使用Result<T,E>来实现。
(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<T, E>
原型:

enum Result<T, E> {
    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");
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
令狐一冲
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
文章
255
粉丝
120
喜欢
308
收藏
128
排名:335
访问:2.8 万
私信
所有博文
社区赞助商