0Pricing
WebAssembly (WASM) for High Performance Apps · 课时

为 WASM 编写 Rust 函数

开发可编译为 WASM 的 Rust 函数,并将其暴露给 JavaScript 环境执行

为 WASM 编写 Rust 函数 是 CoddyKit 上的免费 WebAssembly (WASM) for High Performance Apps 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 WebAssembly (WASM) for High Performance Apps 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 WebAssembly (WASM) for High Performance Apps 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Unlocking Rust for the Web

Welcome back! In the previous lesson, we set up our Rust environment for WebAssembly. Now, let's dive into writing Rust functions that can be used directly in your web applications.

The goal is to expose Rust's performance and safety to JavaScript, making your web apps even more powerful.

Standard Rust Function Syntax

Before exporting, let's quickly recall how standard Rust functions are defined. They use the fn keyword, followed by the function name, parameters with their types, and an optional return type.

  • fn: Declares a function.
  • (param: Type): Defines parameters and their types.
  • -> ReturnType: Specifies the function's return type.

Introducing `#[wasm_bindgen]`

To make a Rust function callable from JavaScript, we use a special attribute from the wasm-bindgen crate: #[wasm_bindgen]. Think of it as a bridge builder!

This attribute tells the wasm-bindgen tool to generate the necessary 'glue code' that allows JavaScript to understand and invoke your Rust function seamlessly.

Your First Exported Function: `add`

Let's write a simple Rust function that adds two integers and expose it to JavaScript. This function will live in your src/lib.rs file.

Notice the #[wasm_bindgen] attribute right above the function definition. This is the magic!

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

Understanding `pub` and `use`

In the previous example, you saw pub fn and use wasm_bindgen::prelude::*;. Let's clarify their roles:

  • pub: This keyword makes the function public, meaning it can be accessed from outside the current module (e.g., by JavaScript).
  • use wasm_bindgen::prelude::*;: This line imports essential items from the wasm-bindgen library, including the #[wasm_bindgen] attribute itself.

Compiling Your Rust to WASM

After writing your Rust code, you'll use the wasm-pack build command (which we briefly mentioned in Lesson 1) to compile it into a WebAssembly module.

wasm-pack handles all the complexity, producing a .wasm file and a JavaScript 'glue' file that simplifies loading and interacting with your Rust functions from JS.

Another Simple Function: `multiply`

Let's add another function to our src/lib.rs. This one will multiply two numbers. The process is identical: define the function, add the #[wasm_bindgen] attribute, and make it pub.

This demonstrates how easy it is to expose multiple Rust functions.

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn multiply(a: i32, b: i32) -> i32 {
    a * b
}

Type Compatibility with JavaScript

When defining functions for WASM, wasm-bindgen automatically handles many common Rust types (like i32, f64) and maps them to their JavaScript equivalents (number).

For more complex types like strings or custom structs, special handling is required, which we'll explore in future lessons. For now, stick to primitive number types.

How JavaScript Accesses Exports

Once compiled, the wasm-pack tool generates a JavaScript file (e.g., my_wasm_lib.js) that acts as an intermediary.

You'll import this JS file into your web project, and it will provide functions like add() and multiply() directly, abstracting away the WASM loading process. This makes using Rust functions feel just like calling regular JavaScript functions.

Test Your Knowledge

What is the primary purpose of the #[wasm_bindgen] attribute in Rust when building for WebAssembly?

Recap: Functions for the Web

Great job! You've learned how to define and expose Rust functions for WebAssembly.

  • Use #[wasm_bindgen] to mark functions for export.
  • Ensure functions are pub.
  • wasm-pack build compiles your Rust into WASM and JS glue.
  • Primitive types like i32 map easily to JavaScript numbers.

Next, we'll dive deeper into how JavaScript loads and executes these WASM modules.

常见问题解答

「为 WASM 编写 Rust 函数」课时是免费的吗?

是的 — 「为 WASM 编写 Rust 函数」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 WebAssembly (WASM) for High Performance Apps 课程的其余内容,请升级到 CoddyKit PRO。 WebAssembly (WASM) for High Performance Apps 课程共包含 4 节课。

「为 WASM 编写 Rust 函数」这节课中我会学到什么?

开发可编译为 WASM 的 Rust 函数,并将其暴露给 JavaScript 环境执行 你通过在浏览器中直接运行的动手代码来练习 WebAssembly (WASM) for High Performance Apps,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 WebAssembly (WASM) for High Performance Apps 需要有经验吗?

无需任何先前经验。CoddyKit 上的 WebAssembly (WASM) for High Performance Apps 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「为 WASM 编写 Rust 函数」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 WebAssembly (WASM) for High Performance Apps 课中编写并运行代码吗?

能。每节 WebAssembly (WASM) for High Performance Apps 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 为 WebAssembly 设置 Rust
  2. 为 WASM 编写 Rust 函数
  3. 使用 `wasm-bindgen` 高效实现 JS 互操作
  4. 跨越 WASM 边界的错误处理
← 返回 WebAssembly (WASM) for High Performance Apps