컴포넌트 임포트 및 재사용하기 (Rust)
인터페이스 임포트하기
앞서 생성한 월드 파일(wit/world.wit)에는 임포트가 지정되어 있지 않습니다. 컴포넌트가 다른 컴포넌트를 사용하는 경우, world.wit 파일을 편집하여 해당 컴포넌트의 인터페이스를 임포트할 수 있습니다.
예를 들어, 이전 튜토리얼에서 설명한 대로 adder 컴포넌트를 생성하고 빌드했으며, 이 컴포넌트를 calculator 컴포넌트에서 사용하려 한다고 가정하겠습니다. 다음은 add 인터페이스를 임포트하는 calculator 월드 예제의 일부입니다:
// in the 'calculator' project
// wit/world.wit
package docs:calculator;
interface calculate {
eval-expression: func(expr: string) -> u32;
}
world calculator {
import docs:adder/add@0.1.0;
export calculate;
}
임포트할 패키지 참조하기
docs:adder 패키지는 다른 프로젝트에 있으므로, 먼저 wkg에 이 패키지를 찾는 방법을 알려 주어야 합니다. 이를 위해 프로젝트에 사용자 지정 wkg.toml을 추가합니다:
[overrides]
"docs:adder" = { path = "../adder/wit" } # directory containing the WIT package
이 구성 파일을 추가한 후 wkg wit fetch를 실행하면, wkg는 패키지 docs:adder를 지정된 경로에서 찾을 수 있다고 가정하고 그 내용을 로컬 프로젝트의 wit/deps 아래로 가져옵니다.
Rust에서 임포트 호출하기
이제 adder의 WIT 파일에 있는 add 선언을 calculator 프로젝트에서 볼 수 있습니다.
calculate 구현에서 임포트한 add 인터페이스를 호출하려면 다음과 같이 하십시오:
#![allow(unused)]
fn main() {
// src/lib.rs
// Generated code that includes both the import stubs for adder functionality
// and the stubs for exports is generated into the `bindings` module below
//
// Note that while wit_bindgen::generate only creates stubs for imports,
// not implementation -- this component will be built with *unsatisfied*
// (but usable) imports (e.g. the add).
mod bindings {
use super::Component;
wit_bindgen::generate!({
generate_all
});
export!(Component);
}
/// The struct from which all implementation will hang
struct Component;
// Implementation of the `docs:calculator/calculate` export
impl bindings::exports::docs::calculator::calculate::Guest for Component {
fn eval_expression(expr: String) -> u32 {
// TODO: Cleverly parse `expr` into values and operations, and evaluate them meticulously.
bindings::docs::calculator::add::add(123, 456)
}
}
}
eval_expression의 구현을 채우고 실제 표현식을 파싱하는 작업은 독자의 연습 과제로 남겨 둡니다.
임포트 충족하기
cargo build를 사용하여 빌드하면 add 인터페이스는 충족되지 않은 상태(즉, 임포트된 상태)로 남습니다.
calculator는 add 인터페이스에 대한 의존성을 갖게 되었지만, 해당 인터페이스의 adder 구현을 링크하지는 않았습니다. 이는 adder 크레이트를 참조하는 것과는 다릅니다(실제로 calculator는 WIT 파일을 구현하는 Rust 프로젝트가 없더라도 add 인터페이스를 임포트할 수 있습니다).
wasm-tools component wit를 실행하여 calculator의 월드를 확인하면 이를 알 수 있습니다:
# Do a release build to prune unused imports (e.g. WASI)
$ cargo build --target=wasm32-wasip2 --release
$ wasm-tools component wit ./target/wasm32-wasip1/release/calculator.wasm
package root:component;
world root {
import docs:adder/add@0.1.0;
export docs:calculator/calculate@0.1.0;
}
임포트가 충족되지 않았으므로, calculator.wasm 컴포넌트는 현재 형태로는 단독으로 실행될 수 없습니다. 다음 단계는 add 임포트를 충족하여 calculate만 익스포트되도록 하고, 컴포넌트를 실행할 수 있게 만드는 것입니다.
다른 컴포넌트의 익스포트를 통해 임포트를 충족하는 과정을 “합성“이라고 합니다. calculator.wasm을 adder.wasm과 합성하여 하나의 독립된 컴포넌트로 만드는 방법에 대한 자세한 내용은 컴포넌트 합성 가이드를 참조하십시오.