Skip to content

Commit d0c4f31

Browse files
committed
添加练习
1 parent 45817a5 commit d0c4f31

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed

_posts/2025-09-19-rust-try.md

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
---
2+
title: rust try练习
3+
---
4+
5+
```rust
6+
#![feature(try_trait_v2)]
7+
#![allow(unused)]
8+
use std::ops::{ControlFlow, FromResidual, Try};
9+
10+
#[derive(Debug)]
11+
enum MyTry {
12+
TOK(Vec<String>),
13+
TERR(Vec<String>),
14+
}
15+
16+
impl FromResidual for MyTry {
17+
/// from的目的是复原对象
18+
fn from_residual(residual: <Self as Try>::Residual) -> Self {
19+
println!("调用 from_residual: {residual:?}");
20+
let mut residual = residual;
21+
residual.push("调用 from_residual".to_string());
22+
MyTry::TERR(residual)
23+
}
24+
}
25+
26+
impl Try for MyTry {
27+
type Output = Vec<String>;
28+
type Residual = Vec<String>;
29+
30+
/// from的目的是复原对象
31+
fn from_output(output: Self::Output) -> Self {
32+
println!("调用 from output: {output:?}");
33+
let mut output = output;
34+
output.push("调用 from_output".to_string());
35+
MyTry::TOK(output)
36+
}
37+
38+
/// 在执行到?时, 调用branch来判断是继续还是返回
39+
/// 继续时, 类型为 Self::Output,
40+
/// 返回时, 类型为 Self,
41+
fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
42+
match self {
43+
MyTry::TOK(ok) => {
44+
println!("branch ok");
45+
let mut ok= ok;
46+
ok.push("被分支ok修改".to_string());
47+
ControlFlow::Continue(ok)
48+
}
49+
MyTry::TERR(err) => {
50+
println!("branch err");
51+
let mut err = err;
52+
err.push("被分支err修改".to_string());
53+
54+
ControlFlow::Break(err)
55+
}
56+
}
57+
}
58+
}
59+
60+
fn try1() -> MyTry {
61+
let r1 = MyTry::TOK(vec!["初始化的数据".to_string()])?;
62+
println!("r1 is {:?}", r1);
63+
64+
65+
MyTry::TOK(r1)
66+
}
67+
68+
fn try2() -> MyTry {
69+
70+
let r2 = MyTry::TERR(vec!["初始化的数据".to_string()])?;
71+
println!("r2 is {:?}", r2);
72+
73+
MyTry::TOK(r2)
74+
}
75+
76+
fn main() {
77+
let rs = try1();
78+
println!("rs: {:?}", rs);
79+
80+
let rs2 = try2();
81+
println!("rs2: {rs2:?}");
82+
}
83+
84+
```

0 commit comments

Comments
 (0)