Rust YouTube Bits

From bibbleWiki
Revision as of 04:06, 8 January 2025 by Iwiseman (talk | contribs) (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...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

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
    }
}