Cómo crear tu primer código WebAssembly con Rust
Apr 09 2023
En este artículo, describiremos qué hacer para crear su primer código WebAssemly. Supongamos que ya ha escuchado algo sobre WebAssembly, pero aún no ha escrito su primer código con esta tecnología.
En este artículo, describiremos qué hacer para crear su primer código WebAssemly.
Supongamos que ya ha escuchado algo sobre WebAssembly, pero aún no ha escrito su primer código con esta tecnología.
Por ahora, vamos a hacer un paquete de inicio simple. Elegí la combinación con el lenguaje de programación Rust porque es atractivo.
Sin más preámbulos, hagámoslo.
Instalar óxido y carga
Rust: lenguaje de programación multiparadigma, de alto nivel y de propósito general (https://www.rust-lang.org/)
Cargo: la herramienta de compilación Rust y el administrador de paquetes (https://crates.io/)
Archivo Init 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
Si tiene problemas para poner en marcha el proyecto, intente consultar mi repositorio de GitHub

![¿Qué es una lista vinculada, de todos modos? [Parte 1]](https://post.nghiatu.com/assets/images/m/max/724/1*Xokk6XOjWyIGCBujkJsCzQ.jpeg)



































