0Pricing
Learn Rust Coding · Aula

Rust para WebAssembly (WASM)

Compile código Rust para WebAssembly, permitindo que módulos de alto desempenho sejam executados em navegadores Web e noutros ambientes de execução WASM.

Rust para WebAssembly (WASM) é uma aula grátis de Learn Rust Coding no CoddyKit. Esta é a aula 2 de 3. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Learn Rust Coding, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Learn Rust Coding inclui 3 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em 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!

Perguntas Frequentes

A aula “Rust para WebAssembly (WASM)” é grátis?

Sim — o texto completo de “Rust para WebAssembly (WASM)” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Learn Rust Coding, atualize para CoddyKit PRO. O curso de Learn Rust Coding inclui 3 aulas no total.

O que vou aprender em “Rust para WebAssembly (WASM)”?

Compile código Rust para WebAssembly, permitindo que módulos de alto desempenho sejam executados em navegadores Web e noutros ambientes de execução WASM. Você pratica Learn Rust Coding com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Learn Rust Coding?

Nenhuma experiência prévia é necessária. Learn Rust Coding no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 2 de 3.

Quanto tempo leva a aula “Rust para WebAssembly (WASM)”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Learn Rust Coding?

Sim. Cada aula de Learn Rust Coding inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Interface de Funções Estrangeiras (FFI)
  2. Rust para WebAssembly (WASM)
  3. Avaliação Comparativa e Otimização do Desempenho
← Voltar para Learn Rust Coding