使用 `wasm-bindgen` 高效实现 JS 互操作
掌握 `wasm-bindgen`,在 Rust WASM 与 JavaScript 之间无缝交换复杂数据结构并实现交互
使用 `wasm-bindgen` 高效实现 JS 互操作 是 CoddyKit 上的免费 WebAssembly (WASM) for High Performance Apps 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 WebAssembly (WASM) for High Performance Apps 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 WebAssembly (WASM) for High Performance Apps 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Unlocking Complex Interop
Welcome to the final lesson on building high-performance WASM with Rust! So far, you've learned to set up Rust for WASM and write basic functions.
But what about exchanging complex data like strings, objects, or arrays? This is where wasm-bindgen comes in. It's a Rust tool that simplifies interaction between Rust and JavaScript.
What is `wasm-bindgen`?
wasm-bindgen is a utility that helps you create JavaScript bindings for Rust WebAssembly modules. It handles the low-level details of passing data types between the two languages.
- Automates FFI: It automatically generates JavaScript glue code and Rust FFI (Foreign Function Interface) declarations.
- Rich Type Support: It allows you to pass more complex types like
String, JavaScript objects, and even DOM elements directly. - Improved Developer Experience: It makes your Rust WASM modules feel more like native JavaScript modules.
Setting Up for `wasm-bindgen`
To use wasm-bindgen, you need to add it as a dependency in your Cargo.toml. You'll also use the wasm-pack tool, which leverages wasm-bindgen to build your WASM module.
Add this to your Cargo.toml:
[dependencies]
wasm-bindgen = "0.2"Then, mark your functions with #[wasm_bindgen].
Exporting Basic Functions
Let's start with a simple function. The #[wasm_bindgen] attribute makes a Rust function available to JavaScript.
Try running this example. The add_numbers function is exposed, and run_add_example demonstrates calling it.
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn add_numbers(a: u32, b: u32) -> u32 {
a + b
}
// This function serves as a runnable entry point for demonstration.
#[wasm_bindgen]
pub fn run_add_example() -> u32 {
add_numbers(10, 5)
}Passing Strings to Rust
One of wasm-bindgen's great features is how it handles strings. You can pass a JavaScript string directly to a Rust function expecting &str or String.
Here, the greet function takes a string argument from JavaScript.
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn greet(name: &str) -> String {
format!("Hello, {}!", name)
}
#[wasm_bindgen]
pub fn run_greet_example() -> String {
greet("CoddyKit User")
}Returning Strings from Rust
Similarly, Rust functions returning a String will automatically be converted into a JavaScript string. This makes working with text across the boundary very natural.
The get_message function returns a Rust String.
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn get_message() -> String {
String::from("This message came from Rust!")
}
#[wasm_bindgen]
pub fn run_get_message_example() -> String {
get_message()
}Exporting Structs as JS Classes
wasm-bindgen can also expose Rust structs as JavaScript classes. This allows you to create and manipulate Rust objects directly from JavaScript.
The User struct below becomes a class in JavaScript, complete with a constructor.
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub struct User {
name: String,
age: u8,
}
#[wasm_bindgen]
impl User {
#[wasm_bindgen(constructor)]
pub fn new(name: String, age: u8) -> User {
User { name, age }
}
}
#[wasm_bindgen]
pub fn create_user_example() -> User {
User::new("Alice".to_string(), 30)
}Adding Methods to JS Classes
Once a Rust struct is exposed as a JavaScript class, you can add methods to its impl block. These methods will be callable directly on the JavaScript object.
Let's add a greet method to our User struct.
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub struct User {
name: String,
age: u8,
}
#[wasm_bindgen]
impl User {
#[wasm_bindgen(constructor)]
pub fn new(name: String, age: u8) -> User {
User { name, age }
}
pub fn greet(&self) -> String {
format!("Hi, my name is {} and I'm {} years old.", self.name, self.age)
}
}
#[wasm_bindgen]
pub fn run_user_greet_example() -> String {
let user = User::new("Bob".to_string(), 25);
user.greet()
}Passing Rust Vectors to JS
wasm-bindgen can also handle basic collection types like Vec for primitive types. It will convert a Rust Vec into a JavaScript array.
This allows you to pass lists of numbers or strings easily.
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn process_numbers(numbers: Vec<u32>) -> Vec<u32> {
numbers.iter().map(|n| n * 2).collect()
}
#[wasm_bindgen]
pub fn run_process_numbers_example() -> Vec<u32> {
let input = vec![1, 2, 3];
process_numbers(input)
}`wasm-bindgen` Interop Check
Which of the following statements about wasm-bindgen are TRUE?
Recap: Mastering Interop
You've now mastered wasm-bindgen, a powerful tool for seamless interaction between Rust and JavaScript in your WebAssembly projects.
- It automates binding generation, making your Rust functions and types easily accessible from JS.
- It enables the exchange of complex data types like strings, structs (as JS classes), and vectors.
- This significantly improves developer experience, letting you write high-performance Rust logic that feels native in a JavaScript environment.
With wasm-bindgen, your Rust WASM modules can become integral, high-performance components of any web application!
常见问题解答
「使用 `wasm-bindgen` 高效实现 JS 互操作」课时是免费的吗?
是的 — 「使用 `wasm-bindgen` 高效实现 JS 互操作」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 WebAssembly (WASM) for High Performance Apps 课程的其余内容,请升级到 CoddyKit PRO。 WebAssembly (WASM) for High Performance Apps 课程共包含 4 节课。
「使用 `wasm-bindgen` 高效实现 JS 互操作」这节课中我会学到什么?
掌握 `wasm-bindgen`,在 Rust WASM 与 JavaScript 之间无缝交换复杂数据结构并实现交互 你通过在浏览器中直接运行的动手代码来练习 WebAssembly (WASM) for High Performance Apps,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 WebAssembly (WASM) for High Performance Apps 需要有经验吗?
无需任何先前经验。CoddyKit 上的 WebAssembly (WASM) for High Performance Apps 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「使用 `wasm-bindgen` 高效实现 JS 互操作」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 WebAssembly (WASM) for High Performance Apps 课中编写并运行代码吗?
能。每节 WebAssembly (WASM) for High Performance Apps 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 为 WebAssembly 设置 Rust
- 为 WASM 编写 Rust 函数
- 使用 `wasm-bindgen` 高效实现 JS 互操作
- 跨越 WASM 边界的错误处理