-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquestion.rs
More file actions
57 lines (48 loc) · 1.06 KB
/
Copy pathquestion.rs
File metadata and controls
57 lines (48 loc) · 1.06 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
#![allow(unused)]
fn f1() -> Result<u32, String> {
println!("f1");
Ok(1)
}
fn f2() -> Result<u32, String> {
println!("f2");
Ok(2)
}
fn f3() -> Result<u32, bool> {
println!("f3");
Ok(3)
}
fn f1_f2_match() -> Result<u32, String> {
// Panic on error
// f1().unwrap();
// f2().unwrap();
let res_1 = f1();
let out_1 = match res_1 {
Ok(num) => num,
Err(_) => {
return Err("error from f1".to_string());
}
};
let res_2 = f2();
let out_2 = match res_2 {
Ok(num) => num,
Err(_) => {
return Err("error from f2".to_string());
}
};
Ok(out_1 + out_2)
}
// Return type must be same (or can be casted) for f1 and f2
fn f1_f2_question() -> Result<u32, String> {
let out_1 = f1()?;
let out_2 = f2()?;
let out_3 = f3().map_err(|err| err.to_string())?;
Ok(out_1 + out_2)
}
fn main() {
// Match
let res = f1_f2_match();
println!("{:?}", res);
// Question operator
let res = f1_f2_question();
println!("{:?}", res);
}