Rust YouTube Bits: Difference between revisions

From bibbleWiki
Jump to navigation Jump to search
Line 69: Line 69:
fn call_test() -> Result<i32, MyApiError> {
fn call_test() -> Result<i32, MyApiError> {
     test().map_err(|_| MyApiError)
     test().map_err(|_| MyApiError)
}
</syntaxhighlight>
=Rust with Yew and Wasm=
This was another video from Code to the Moon and demonstrated using rust as a front-end using yew [[https://yew.rs/]]. Not sure it will catch on. No release last year 2024. You need to cargo install trunk and here is the code from [[https://github.com/MoonKraken/youtube/tree/main/RustFrontEnd Code to the Moon]], here to show how easy it was
<syntaxhighlight lang="rs">
use yew::prelude::*;
struct Model {
    value: i64
}
#[function_component(App)]
fn app() -> Html {
    let state = use_state(|| Model {
        value: 0
    });
    let onclick = {
        let state = state.clone();
        Callback::from(move |_| {
            state.set(Model {
                value: state.value + 1
            })
        })
    };
    html! {
        <div>
            <button {onclick}>
                { "+1" }
            </button>
            <p>{ state.value }</p>
        </div>
    }
}
fn main() {
    yew::start_app::<App>();
}
}
</syntaxhighlight>
</syntaxhighlight>

Revision as of 05:57, 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)
}

Rust with Yew and Wasm

This was another video from Code to the Moon and demonstrated using rust as a front-end using yew [[1]]. Not sure it will catch on. No release last year 2024. You need to cargo install trunk and here is the code from [Code to the Moon], here to show how easy it was

use yew::prelude::*;

struct Model {
    value: i64
}

#[function_component(App)]
fn app() -> Html {
    let state = use_state(|| Model {
        value: 0
    });

    let onclick = {
        let state = state.clone();

        Callback::from(move |_| {
            state.set(Model {
                value: state.value + 1
            })
        })
    };

    html! {
        <div>
            <button {onclick}>
                { "+1" }
            </button>
            <p>{ state.value }</p>
        </div>
    }
}

fn main() {
    yew::start_app::<App>();
}