0Pricing
Learn Rust Coding · Lección

De Rust a WebAssembly (WASM)

Compile código Rust a WebAssembly para permitir que módulos de alto rendimiento se ejecuten en navegadores web y otros runtimes de WASM.

De Rust a WebAssembly (WASM) es una lección gratuita de Learn Rust Coding en CoddyKit. Esta es la lección 2 de 3. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Learn Rust Coding, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Learn Rust Coding incluye 3 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

What is WebAssembly (WASM)?

WebAssembly, or WASM, is a binary instruction format for a stack-based virtual machine. It's designed to be a portable compilation target for high-level languages like Rust, C/C++, and Go.

Think of it as a low-level assembly-like language that runs efficiently in web browsers and other environments. It allows you to run performance-critical code at near-native speeds.

Rust's Advantages for WASM

Rust is an excellent choice for WebAssembly development due to its unique strengths:

  • Performance: Rust is known for its speed, close to C/C++.
  • Memory Safety: Rust's ownership system prevents common bugs without a garbage collector.
  • Small Binaries: Rust's minimal runtime leads to compact WASM modules.
  • Tooling: Excellent support with tools like wasm-pack and wasm-bindgen.

Setting Up Your WASM Tools

To compile Rust to WebAssembly, you'll primarily use wasm-pack. It's a command-line tool that handles the entire build process.

You'll also use wasm-bindgen, a Rust crate and CLI tool that facilitates high-level interactions between WASM modules and JavaScript.

To install wasm-pack, open your terminal and run:

cargo install wasm-pack

Your First WASM Project

Let's create a new Rust project tailored for WebAssembly. We'll use cargo generate with a specific template:

cargo install cargo-generate
cargo generate --git https://github.com/rustwasm/wasm-pack-template

Follow the prompts to name your project. This sets up a lib.rs file ready for WASM code and a www directory for a simple web interface.

Rust Function for JavaScript

To make a Rust function callable from JavaScript, we use the #[wasm_bindgen] attribute from the wasm-bindgen crate.

This attribute instructs wasm-bindgen to generate the necessary glue code for JavaScript to interact with your Rust function.

use wasm_bindgen::prelude::*;

// This attribute makes the `greet` function available to JavaScript.
#[wasm_bindgen]
pub fn greet(name: &str) -> String {
    format!("Hello, {}!", name)
}

// In a WASM library, `main` is not used. This code is compiled to a .wasm module.

Integrate WASM with JavaScript

After writing your Rust code, you build it into a WASM module using wasm-pack build. This command creates a pkg directory with your .wasm file and JS glue code.

Then, in your JavaScript, you can easily import and use the exported Rust functions:

// www/index.js (simplified)
import { greet } from "../pkg/your_project_name"; // Adjust path

// Call the Rust function
const message = greet("CoddyKit Learner");
console.log(message); // Outputs: "Hello, CoddyKit Learner!"

// You'd typically connect this to HTML elements.

Rust Calling JavaScript

Rust can also call JavaScript functions. You declare them in an extern "C" block and use #[wasm_bindgen] to map them to JS global objects or functions.

The js_namespace argument lets you specify where to find the function in the JavaScript environment, like the console object.

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
extern "C" {
    // Import JS console.log as a Rust function named 'log'
    #[wasm_bindgen(js_namespace = console)]
    fn log(s: &str);

    // You can import other JS functions too
    #[wasm_bindgen(js_name = alert)]
    fn js_alert(s: &str);
}

#[wasm_bindgen]
pub fn log_and_alert_from_rust(message: &str) {
    log(&format!("Rust log: {}", message));
    js_alert(&format!("Rust alert: {}", message));
}

Passing Strings Between Rust & JS

wasm-bindgen intelligently handles common data types like numbers and booleans. For strings, it uses UTF-8 encoding.

When you pass a &str or String from Rust, wasm-bindgen converts it to a JavaScript String, and vice-versa. This abstraction makes interop smooth.

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn uppercase_and_reverse(s: String) -> String {
    s.to_uppercase().chars().rev().collect()
}

// This function takes a String, processes it, and returns a new String.
// wasm-bindgen handles the conversion to/from JS strings.

WASM Outside the Browser

While often associated with web browsers, WebAssembly isn't limited to them! WASM runtimes exist for many environments, opening up new possibilities:

  • Serverless Functions: Deploy fast, isolated functions.
  • Blockchain: Smart contracts execution.
  • Plugins/Extensions: Securely extend applications.
  • Desktop Apps: Embed high-performance modules.

This expands Rust's reach far beyond traditional systems programming.

WebAssembly Key Concepts

Let's check your understanding of Rust and WebAssembly.

Recap: Rust to WASM

You've learned how to bring Rust's performance and safety to WebAssembly!

  • WASM provides a fast, portable runtime for compiled code.
  • Rust excels at WASM thanks to its performance, small binaries, and safety.
  • Tools like wasm-pack and wasm-bindgen simplify the development process.
  • You can easily export Rust functions to JavaScript and import JavaScript functions into Rust.
  • WASM's applications extend far beyond just web browsers.

Keep exploring to build powerful, high-performance web and non-web applications with Rust!

Preguntas frecuentes

¿La lección «De Rust a WebAssembly (WASM)» es gratis?

Sí — el texto completo de «De Rust a WebAssembly (WASM)» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Learn Rust Coding, actualiza a CoddyKit PRO. El curso de Learn Rust Coding incluye 3 lecciones en total.

¿Qué aprenderé en «De Rust a WebAssembly (WASM)»?

Compile código Rust a WebAssembly para permitir que módulos de alto rendimiento se ejecuten en navegadores web y otros runtimes de WASM. Practicas Learn Rust Coding con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Learn Rust Coding?

No se requiere experiencia previa. Learn Rust Coding en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 3.

¿Cuánto tiempo toma la lección «De Rust a WebAssembly (WASM)»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Learn Rust Coding?

Sí. Cada lección de Learn Rust Coding incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Interfaz de funciones foráneas (FFI)
  2. De Rust a WebAssembly (WASM)
  3. Benchmarking y ajuste del rendimiento
← Volver a Learn Rust Coding