Upgrade to Pro — share decks privately, control downloads, hide ads and more …

RustでWebフロント作れるらしい

Sponsored · Your Podcast. Everywhere. Effortlessly. Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.

 RustでWebフロント作れるらしい

Avatar for YingZhi "Harrison" Huang

YingZhi "Harrison" Huang

March 10, 2024
Tweet

Transcript

  1. Reactでカウンターアプリを作ってみると... function Counter() { const [count, setCount] = useState(0); const

    incrementCount = () => { setCount(count + 1); }; return ( <div> <h2>Counter: {count}</h2> <button onClick={incrementCount}>+1</button> </div> ); }
  2. Rust(Yew)の場合... use yew::prelude::*; #[function_component(UseState)] fn state() -> Html { let

    counter = use_state(|| 0); let onclick = { let counter = counter.clone(); Callback::from(move |_| counter.set(*counter + 1)) }; html! { <div> <button {onclick}>{ "Increment value" }</button> <p> <b>{ "Current value: " }</b> { *counter } </p> </div> } }
  3. WasmでのDOM操作 • WasmではDOM操作するAPIを提供してい る • RustをWasmで動かす場合、 wasm_bindgenとweb_sysを使用すると、 Wasmで実行する際にDOM操作することが できる •

    Yewもこの方法で仮想DOMを実装した模 様 use wasm_bindgen::prelude::*; use web_sys::{window, Document, HtmlElement}; #[wasm_bindgen(start)] pub fn run() -> Result<(), JsValue> { let window = window().expect("should have a Window"); let document = window.document().expect("should have a Document"); let div = document.create_element("div")?; div.set_inner_html("Hello from Rust!"); let body = document.body().expect("document should have a body"); body.append_child(&div as &dyn web_sys::Node)?; Ok(()) }
  4. まとめ • Yewは、Rust製のWebフレームワーク ◦ Reactのような開発体験で、 RustのコードだけでWebフロントの開発ができる • バイナリはWasm経由でブラウザ上で実行している ◦ Wasmはブラウザ上で実行できるバイナリ形式である

    • WasmではDOM操作を可能にするAPIを提供されている • YewのHTMLライクの構文は、Rustのマクロ機能によって実現され、宣言的 UIの実装を可能にしている