阅读量:85
在 Debian 中安装和使用 Rust 编译器的步骤如下:
安装 Rust 编译器
- 更新包列表:
sudo apt update
- 安装 Rust 工具链:
sudo apt install rustc cargo
- 验证安装:
rustc --version
cargo --version
使用 Cargo 管理 Rust 项目
- 创建新项目:
cargo new hello_world
cd hello_world
- 构建项目:
cargo build
- 运行项目:
cargo run
示例:创建和运行一个简单的 Rust WebAssembly 项目
- 安装 WebAssembly 二进制工具包 (wabt):
sudo apt install wabt
- 安装
wasm-bindgen:
cargo install wasm-bindgen-cli
- 创建一个新的 Rust WebAssembly 项目:
cargo new wasm_example
cd wasm_example
- 在
Cargo.toml中添加依赖:
[dependencies]
wasm-bindgen = "0.2"
- 编写 Rust 代码:
在
src/lib.rs中:
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
- 构建和运行 WebAssembly 项目:
cargo build --target wasm32-unknown-unknown --release
wasm-bindgen target/wasm32-unknown-unknown/release/wasm_example.wasm --out-dir ./pkg --target web
- 在 HTML 中使用生成的 WebAssembly 模块:
创建一个
index.html文件:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Rust WebAssembly Example</title>
</head>
<body>
<script type="module">
import init, { add } from './pkg/wasm_example.js';
async function run() {
await init();
const result = add(2, 3);
console.log(`2 + 3 = ${result}`);
}
run();
</script>
</body>
</html>
- 使用一个简单的 HTTP 服务器运行项目:
python3 -m http.server
在浏览器中打开 http://localhost:8000 查看结果。
以上步骤涵盖了在 Debian 上安装 Rust 编译器、使用 Cargo 管理项目、创建和运行一个简单的 Rust WebAssembly 项目的完整流程。