Rust YouTube Bits
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
}
}