-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror_handle.rs
More file actions
79 lines (63 loc) · 1.62 KB
/
Copy patherror_handle.rs
File metadata and controls
79 lines (63 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
Rust 中的错误主要分为两类:
1. 可恢复错误 -> Result<T, E>
2. 不可恢复错误 -> panic!
*/
use std::{
any::Any,
io::{self, Write},
};
// 触发 panic 的两种方式
// 1. 主动触发
pub fn panic_active_trigger() {
// panic!("主动触发");
}
// 2. 被动触发
pub fn panic_passive_triger() {
// let v = vec![1, 2, 3];
// v[99]; // 发生越界
}
// 启用栈展开
// Windows -> CMD -> set RUST_BACKTRACE=1 && cargo run
// -> Powershell -> $env:RUST_BACKTRACE=1; cargo run
// Linux -> RUST_BACKTRACE=1 cargo run
pub fn ip_parse() {
use std::net::IpAddr;
let local: IpAddr = "127.0.0.1".parse().unwrap();
println!("{}", local.is_ipv4());
}
pub fn panic_macro() {
panic!();
}
pub fn test_result_enum() {
use std::fs::File;
let f = File::open("hello_world.txt");
let f = match f {
Ok(f) => f,
Err(_) => match File::create("hello_world.txt") {
Ok(f) => f,
Err(error) => {
panic!("{}", error);
}
},
};
println!("{:?}", f.type_id());
}
pub fn error_propagation() {
use std::fs::File;
fn write_to_file(filename: &str) -> Result<usize, io::Error> {
let mut f = match File::open(filename) {
Ok(f) => f,
Err(e) => return Err(e),
};
let s = "hello world";
match writeln!(f, "{}", s) {
Ok(_) => Ok(s.len()),
Err(e) => return Err(e),
}
}
match write_to_file("hello_world.txt") {
Ok(n) => println!("size = {}", n),
Err(e) => println!("{}", e),
}
}