Rust YouTube Bits: Difference between revisions
Jump to navigation
Jump to search
Created page with "=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 <syntaxhighlight lang="rs"> struct MyBox<T>(T); impl<T> MyBox<T> { fn new(x: T) -> MyBox<T> { MyBox(x) } } fn main() { pri..." |
No edit summary |
||
Line 31: | Line 31: | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
=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 | |||
<syntaxhighlight lang="rs"> | |||
fn is_normal<T: Sized + Send + Sync + Unpin>() {} | |||
#[test] | |||
fn is_normal_types() { | |||
is_normal::<User>(); | |||
} | |||
</syntaxhighlight> | |||
They also mentioned implementing these where applicable and possible making in a feature to remove dependency on serde. | |||
*Serialize | |||
*Deserialize |
Revision as of 04:59, 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