Skip to content

Commit 5decd8d

Browse files
authored
And more stream-2025-04-16.md.
1 parent 1aa1d7b commit 5decd8d

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

stream-2025-04-16.md

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,3 +159,65 @@ fn main() {
159159
o = None;
160160
}
161161
```
162+
163+
Matching and error handling: [link](https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=9a97bfd6781f5f31a0225da44df65814).
164+
165+
```rust
166+
use std::error::Error;
167+
use std::io::{self, Write}; // Note: nontrivial import of `Write` for `flush` to work!
168+
use std::fmt::{Display, Formatter};
169+
170+
#[derive(Debug)]
171+
struct FooError;
172+
173+
impl Display for FooError {
174+
fn fmt(&self, ostream: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
175+
write!(ostream, "triggered the FooError")
176+
}
177+
}
178+
179+
impl Error for FooError {}
180+
181+
// Note: no need in `Debug` since `match` analyzes every option, no generic `{:?}` printing.
182+
// #[derive(Debug)]
183+
enum HalfResult {
184+
Halved(i32),
185+
Negative
186+
}
187+
188+
// Note to C++ folks: `Box<dyn Error>` is literally `std::unique_ptr<ErrorBaseClass>` =)
189+
// Since there's more than one error type to handle.
190+
fn half(s: &str) -> Result<Option<HalfResult>, Box<dyn Error>> {
191+
if s == "foo" {
192+
Err(Box::new(FooError))
193+
} else {
194+
// Question mark to early-return if parse failed.
195+
let x = s.parse::<i32>()?;
196+
println!("Parsed as i32({x}).");
197+
if x < 0 {
198+
Ok(Some(HalfResult::Negative))
199+
} else if x % 2 != 0 {
200+
Ok(None)
201+
} else {
202+
Ok(Some(HalfResult::Halved(x / 2)))
203+
}
204+
}
205+
}
206+
207+
fn main() -> Result<(), Box<dyn Error>> {
208+
print!("Enter a number: ");
209+
io::stdout().flush()?;
210+
let mut input = String::new();
211+
io::stdin().read_line(&mut input)?;
212+
println!("");
213+
214+
match half(input.trim()) {
215+
Ok(Some(HalfResult::Halved(v))) => println!("OK, halved: {v}."),
216+
Ok(Some(HalfResult::Negative)) => println!("Was negative."),
217+
Ok(None) => println!("Gotta be odd."),
218+
Err(e) => println!("Error: {e}.")
219+
}
220+
221+
Ok(())
222+
}
223+
```

0 commit comments

Comments
 (0)