Rust e Wasm
Perché Rust per Wasm?
Rust è attualmente il linguaggio con il miglior supporto per WebAssembly (Mozilla è dietro entrambi).
- Zero Cost Abstractions: Codice veloce quanto C++.
- Memory Safety: Niente segfaults o memory leaks.
- wasm-pack: Tooling eccezionale.
Setup (wasm-pack)
- Installa Rust (rustup).
- Installa wasm-pack: ```bash cargo install wasm-pack ```
Esempio
Crea un progetto lib: cargo new --lib hello-wasm
In Cargo.toml:
```toml
[lib]
crate-type = [“cdylib”]
[dependencies] wasm-bindgen = “0.2” ```
In src/lib.rs:
```rust use wasm_bindgen::prelude::*;
#[wasm_bindgen] extern “C” { fn alert(s: &str); // Importa la funzione alert da JS }
#[wasm_bindgen] pub fn greet(name: &str) { alert(&format!(“Hello, {}!”, name)); } ```
Build
```bash wasm-pack build --target web ```
Questo genererà una cartella pkg con il file .wasm e un wrapper JavaScript (hello_wasm.js) che gestisce automaticamente il passaggio di stringhe e oggetti tra JS e Rust (che hanno gestioni di memoria diverse).