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 协议》,转载必须注明作者和本文链接
推荐文章: