Skip to content

Commit 26e8bb3

Browse files
authored
Create try_from.rs
1 parent eb1255d commit 26e8bb3

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

rust/try_from.rs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
#[derive(Debug, Clone, Copy)]
2+
pub enum ABC {
3+
A,
4+
B,
5+
C
6+
}
7+
8+
impl TryFrom<i32> for ABC {
9+
type Error = ();
10+
11+
fn try_from(n: i32) -> Result<Self, Self::Error> {
12+
match n {
13+
0 => Ok(ABC::A),
14+
1 => Ok(ABC::B),
15+
2 => Ok(ABC::C),
16+
_ => Err(())
17+
}
18+
}
19+
}
20+
21+
fn add(a: i64, b: i64) -> i64 {
22+
a + b
23+
}
24+
25+
fn main() {
26+
let abc: Result<ABC, ()> = TryFrom::try_from(3);
27+
28+
match abc {
29+
Ok(inner) => println!("{:?}", inner),
30+
Err(()) => println!("can't convert to ABC")
31+
}
32+
33+
println!("{}", add(4, 5));
34+
println!("{:?}", abc);
35+
}

0 commit comments

Comments
 (0)