Come creare il tuo primo codice WebAssembly con Rust
Apr 09 2023
In questo articolo, descriveremo cosa fare per creare il tuo primo codice WebAssemly. Supponiamo che tu abbia già sentito parlare di WebAssembly, ma non hai ancora scritto il tuo primo codice con questa tecnologia.
In questo articolo, descriveremo cosa fare per creare il tuo primo codice WebAssemly.
Supponiamo che tu abbia già sentito parlare di WebAssembly, ma non hai ancora scritto il tuo primo codice con questa tecnologia.
Per ora, creeremo un semplice starter pack. Ho scelto la combinazione con il linguaggio di programmazione Rust perché è interessante.
Senza ulteriori indugi, facciamolo.
Installa Rust e Cargo
Rust: linguaggio di programmazione multi-paradigma, di alto livello e generico (https://www.rust-lang.org/)
Cargo: lo strumento di compilazione e gestore di pacchetti di Rust (https://crates.io/)
Avviare il file Cargo.toml
cargo init --name rust_wasm_starter --lib
# Cargo.toml
[package]
name = "rust_wasm_starter"
version = "0.1.0"
edition = "2021"
[dependencies]
cargo add wasm-bindgen
# Cargo.toml
[package]
name = "rust_wasm_starter"
version = "0.1.0"
edition = "2021"
[dependencies]
wasm-bindgen = "0.2.84"
cargo install wasm-pack
[lib]
crate-type = ["cdylib", "rlib"]
use wasm_bindgen::prelude::wasm_bindgen;
#[wasm_bindgen]
pub fn add(a: usize, b: usize) -> usize {
return a + b
}
wasm-pack build --release --target web
npm init
// package.json
{
"name": "rust-wasm-starter",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {},
"author": "",
"license": "ISC"
}
npm i http-server --save
"scripts": {
"start": "http-server -a localhost -p 5200",
"build": "wasm-pack build --release --target web"
}
import init from "./pkg/rust_wasm_starter.js";
import {add} from "../pkg/rust_wasm_starter.js";
function run() {
console.log(add(5, 5));
}
init().then(run)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Rust Wasm Starter</title>
<script type="module" src="./index.js"></script>
</head>
<body>
See the result in the console.
</body>
</html>
npm run start
Starting up http-server, serving ./
http-server version: 14.1.1
CORS: disabled
Cache: 3600 seconds
Connection Timeout: 120 seconds
Directory Listings: visible
AutoIndex: visible
Serve GZIP Files: false
Serve Brotli Files: false
Default File Extension: none
Available on:
http://localhost:5200
Hit CTRL-C to stop the server
Se hai problemi a far funzionare il progetto, prova a controllare il mio repository GitHub

![Che cos'è un elenco collegato, comunque? [Parte 1]](https://post.nghiatu.com/assets/images/m/max/724/1*Xokk6XOjWyIGCBujkJsCzQ.jpeg)



































