debian

Debian中Rust编译器使用指南

小樊
53
2025-04-24 07:36:14
栏目: 编程语言

在 Debian 中安装和使用 Rust 编译器的步骤如下:

安装 Rust 编译器

  1. 更新包列表
sudo apt update
  1. 安装 Rust 工具链
sudo apt install rustc cargo
  1. 验证安装
rustc --version
cargo --version

使用 Cargo 管理 Rust 项目

cargo new hello_world
cd hello_world
cargo build
cargo run

示例:创建和运行一个简单的 Rust WebAssembly 项目

  1. 安装 WebAssembly 二进制工具包 (wabt)
sudo apt install wabt
  1. 安装 wasm-bindgen
cargo install wasm-bindgen-cli
  1. 创建一个新的 Rust WebAssembly 项目
cargo new wasm_example
cd wasm_example
  1. Cargo.toml 中添加依赖
[dependencies]
wasm-bindgen = "0.2"
  1. 编写 Rust 代码: 在 src/lib.rs 中:
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}
  1. 构建和运行 WebAssembly 项目
cargo build --target wasm32-unknown-unknown --release
wasm-bindgen target/wasm32-unknown-unknown/release/wasm_example.wasm --out-dir ./pkg --target web
  1. 在 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>
  1. 使用一个简单的 HTTP 服务器运行项目
python3 -m http.server

在浏览器中打开 http://localhost:8000 查看结果。

以上步骤涵盖了在 Debian 上安装 Rust 编译器、使用 Cargo 管理项目、创建和运行一个简单的 Rust WebAssembly 项目的完整流程。

0
看了该问题的人还看了