Rust YouTube Bits: Difference between revisions
No edit summary |
|||
Line 51: | Line 51: | ||
*Serialize | *Serialize | ||
*Deserialize | *Deserialize | ||
=Handling Option and Result and Error= | |||
This was quite a nice revisit known tricks from Code to the Moon. I never knew of these | |||
*ok_or | |||
*unwrap_or | |||
General learnings are | |||
*unwrap unwraps an Option or Result | |||
*.ok converts between Result and Option | |||
*.map converts to the same container but with a different type e.g. | |||
<syntaxhighlight lang="rs"> | |||
struct MyApiError; | |||
fn test() -> Result<i32, ParseIntError> { | |||
let x: i32 = "5".parse()?; | |||
Ok(x) | |||
} | |||
fn call_test() -> Result<i32, MyApiError> { | |||
test().map_err(|_| MyApiError) | |||
} | |||
</syntaxhighlight> |
Revision as of 05:42, 8 January 2025
Introduction
As I strive to improve I wanted a page for just stuff I watch on YouTube
Deref
Rust list c++ has a deference operator. You can deference with a *. But with wonderful rust you can make one. In the video from The Dev Method, they made an implementation of a box (smart pointer) and demonstrated how to do this
struct MyBox<T>(T);
impl<T> MyBox<T> {
fn new(x: T) -> MyBox<T> {
MyBox(x)
}
}
fn main() {
println!("Hello, world!");
let x = 5;
let y = MyBox::new(x);
assert_eq!(5, x);
assert_eq!(5, *y); // Error no deref
}
To solve this we implement the deref trait
use std::ops::Deref;
impl<T> Deref for MyBox<T> {
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
Patterns
From Let's get rust they were very keen to stress you should implement
- Debug
- Clone
- Default
- PartialEq
They also mentioned
- Send
- Sync
For the Send and Sync they suggested adding a test to make sure send, sync are implemented
fn is_normal<T: Sized + Send + Sync + Unpin>() {}
#[test]
fn is_normal_types() {
is_normal::<User>();
}
They also mentioned implementing these where applicable and possible making in a feature to remove dependency on serde.
- Serialize
- Deserialize
Handling Option and Result and Error
This was quite a nice revisit known tricks from Code to the Moon. I never knew of these
- ok_or
- unwrap_or
General learnings are
- unwrap unwraps an Option or Result
- .ok converts between Result and Option
- .map converts to the same container but with a different type e.g.
struct MyApiError;
fn test() -> Result<i32, ParseIntError> {
let x: i32 = "5".parse()?;
Ok(x)
}
fn call_test() -> Result<i32, MyApiError> {
test().map_err(|_| MyApiError)
}