0Pricing
WebAssembly (WASM) for High Performance Apps · 강의

WASM용 Rust 함수 작성

WASM으로 컴파일하고 JavaScript 환경에 노출하여 실행할 수 있는 Rust 함수를 개발합니다.

WASM용 Rust 함수 작성은(는) CoddyKit의 무료 WebAssembly (WASM) for High Performance Apps 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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 함수 작성” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 WebAssembly (WASM) for High Performance Apps 강의 전체를 잠금 해제할 수 있습니다. WebAssembly (WASM) for High Performance Apps 강의에는 총 4개의 강의가 포함되어 있습니다.

“WASM용 Rust 함수 작성”에서 뭘 배우나요?

WASM으로 컴파일하고 JavaScript 환경에 노출하여 실행할 수 있는 Rust 함수를 개발합니다. 브라우저에서 직접 실행하는 실습 코드로 WebAssembly (WASM) for High Performance Apps을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

WebAssembly (WASM) for High Performance Apps을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 WebAssembly (WASM) for High Performance Apps은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“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(으)로 돌아가기