Rust 完整指南:从安装到打包发布

在这里插入图片描述

目录


Rust 简介

Rust 是一门系统编程语言,专注于三个方面:安全性速度并发性。它的设计目标是提供内存安全保证,同时不需要垃圾回收器。

为什么选择 Rust?

  • 内存安全:通过所有权系统在编译时防止内存错误
  • 零成本抽象:高级特性不会带来运行时开销
  • 并发安全:编译器帮助防止数据竞争
  • 现代工具链:Cargo 提供了出色的开发体验
  • 活跃的社区:丰富的生态系统和友好的社区支持

安装 Rust

Rust 使用 rustup 工具来管理 Rust 版本和相关工具。这是安装 Rust 的推荐方式。

Windows 安装

方法一:使用 rustup-init.exe(推荐)
  1. 下载安装程序

    访问 https://rustup.rs/ 或直接下载:

    https://static.rust-lang.org/rustup/dist/x86_64-pc-windows-msvc/rustup-init.exe
    
  2. 运行安装程序

    双击 rustup-init.exe,你会看到以下选项:

    1) Proceed with installation (default)
    2) Customize installation
    3) Cancel installation
    
  3. 选择安装选项

    • 默认安装:输入 1 或直接按回车
    • 自定义安装:输入 2 可以选择安装路径、工具链等
  4. 安装 C++ 构建工具

    Rust 在 Windows 上需要 Microsoft C++ 构建工具。安装程序会提示你安装:

    • 安装 Visual Studio 2022(推荐选择 “Desktop development with C++”)
    • 或者安装 Build Tools for Visual Studio 2022

    下载地址:https://visualstudio.microsoft.com/downloads/

  5. 完成安装

    安装完成后,重启终端或命令提示符。

方法二:使用包管理器

使用 Scoop:

scoop install rustup

使用 Chocolatey:

choco install rustup.install

Linux 和 macOS 安装

一键安装脚本

打开终端,运行以下命令:

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
安装步骤详解
  1. 运行安装脚本

    脚本会下载并运行 rustup-init,然后显示安装选项。

  2. 选择安装选项

    1) Proceed with installation (default)
    2) Customize installation
    3) Cancel installation
    

    通常选择默认安装(输入 1 或按回车)。

  3. 配置环境变量

    安装程序会自动将以下内容添加到你的 shell 配置文件(如 ~/.bashrc~/.zshrc):

    export PATH="$HOME/.cargo/bin:$PATH"
    
  4. 使配置生效

    source $HOME/.cargo/env
    

    或者重启终端。

Linux 特定依赖

某些 Linux 发行版可能需要额外的依赖:

Ubuntu/Debian:

sudo apt update
sudo apt install build-essential

Fedora/RHEL/CentOS:

sudo dnf install gcc

Arch Linux:

sudo pacman -S base-devel

验证安装

安装完成后,验证 Rust 是否正确安装:

# 检查 rustc(Rust 编译器)版本
rustc --version

# 检查 cargo(包管理器)版本
cargo --version

# 检查 rustup 版本
rustup --version

预期输出示例:

rustc 1.75.0 (82e1608df 2023-12-21)
cargo 1.75.0 (1d8b05cdd 2023-11-20)
rustup 1.26.0 (5af9b9484 2023-04-05)

配置镜像源

在中国大陆,建议配置镜像源以加速下载。

配置 Cargo 镜像

创建或编辑 ~/.cargo/config.toml(Windows: %USERPROFILE%\.cargo\config.toml):

[source.crates-io]
replace-with = 'ustc'

[source.ustc]
registry = "sparse+https://mirrors.ustc.edu.cn/crates.io-index/"

# 或使用字节跳动源
[source.rsproxy]
registry = "https://rsproxy.cn/crates.io-index"

# 或使用清华源
[source.tuna]
registry = "https://mirrors.tuna.tsinghua.edu.cn/git/crates.io-index.git"
配置 rustup 镜像

在环境变量中设置:

Linux/macOS (添加到 ~/.bashrc 或 ~/.zshrc):

export RUSTUP_DIST_SERVER=https://mirrors.ustc.edu.cn/rust-static
export RUSTUP_UPDATE_ROOT=https://mirrors.ustc.edu.cn/rust-static/rustup

Windows (PowerShell):

$env:RUSTUP_DIST_SERVER="https://mirrors.ustc.edu.cn/rust-static"
$env:RUSTUP_UPDATE_ROOT="https://mirrors.ustc.edu.cn/rust-static/rustup"

Rust 工具链管理

rustup 提供了强大的工具链管理功能。

更新 Rust

# 更新到最新稳定版
rustup update

# 更新特定工具链
rustup update stable
rustup update nightly

安装不同版本

# 安装稳定版
rustup install stable

# 安装 nightly 版本
rustup install nightly

# 安装特定版本
rustup install 1.75.0

设置默认工具链

# 设置默认工具链为稳定版
rustup default stable

# 设置为 nightly 版本
rustup default nightly

工具链覆盖

为特定项目使用不同的工具链:

# 在项目目录中
rustup override set nightly

# 查看当前覆盖
rustup override list

# 移除覆盖
rustup override unset

安装组件

# 安装 Rust 源码(用于 IDE 跳转)
rustup component add rust-src

# 安装 rustfmt(代码格式化)
rustup component add rustfmt

# 安装 clippy(代码检查工具)
rustup component add clippy

# 安装 rust-analyzer(LSP 服务)
rustup component add rust-analyzer

目标平台

# 列出所有可用目标
rustup target list

# 添加交叉编译目标
rustup target add x86_64-pc-windows-gnu
rustup target add x86_64-unknown-linux-musl
rustup target add aarch64-unknown-linux-gnu

# 列出已安装的目标
rustup target list --installed

创建第一个项目

使用 Cargo 创建项目

# 创建二进制项目(可执行程序)
cargo new my_project

# 创建库项目
cargo new my_library --lib

# 进入项目目录
cd my_project

项目结构

my_project/
├── Cargo.toml          # 项目配置文件
├── Cargo.lock          # 依赖锁文件(自动生成)
├── src/
│   └── main.rs         # 主源文件
└── target/             # 编译输出目录(自动生成)

Cargo.toml 文件详解

[package]
name = "my_project"           # 项目名称
version = "0.1.0"             # 版本号
edition = "2021"              # Rust 版次
authors = ["Your Name <you@example.com>"]
description = "A sample project"
license = "MIT"
repository = "https://github.com/username/my_project"

[dependencies]
# 项目依赖将在这里列出

[dev-dependencies]
# 开发和测试依赖

[build-dependencies]
# 构建脚本依赖

[profile.release]
# 发布配置
opt-level = 3                 # 优化级别 0-3
lto = true                    # 链接时优化
codegen-units = 1             # 减少并行以提高优化

简单的 Hello World

src/main.rs:

fn main() {
    println!("Hello, Rust!");
}

编译 Rust 程序

使用 rustc 直接编译

rustc 是 Rust 编译器,可以直接编译单个文件。

基本编译
# 编译单个文件
rustc main.rs

# 指定输出文件名
rustc main.rs -o my_program

# 在 Windows 上会生成 my_program.exe
# 在 Linux/macOS 上会生成 my_program
编译选项
# 优化编译(-O 或 --opt-level)
rustc -O main.rs

# 指定优化级别(0, 1, 2, 3)
rustc -C opt-level=3 main.rs

# 编译为库
rustc --crate-type=lib mylib.rs

# 显示详细信息
rustc --verbose main.rs

# 生成汇编代码
rustc --emit=asm main.rs

# 生成 LLVM IR
rustc --emit=llvm-ir main.rs

使用 Cargo 编译

Cargo 是 Rust 的构建系统和包管理器,是推荐的编译方式。

基本命令
# 检查代码(快速检查语法错误,不生成可执行文件)
cargo check

# 编译项目(debug 模式)
cargo build

# 编译并运行
cargo run

# 编译为发布版本
cargo build --release

# 运行发布版本
cargo run --release
输出位置
# Debug 版本输出到
target/debug/my_project

# Release 版本输出到
target/release/my_project

编译模式详解

Debug 模式(默认)
cargo build

特点:

  • 快速编译
  • 包含调试信息
  • 不进行优化
  • 文件体积较大
  • 运行速度较慢
  • 适合开发阶段
Release 模式
cargo build --release

特点:

  • 编译时间较长
  • 移除调试信息
  • 完全优化
  • 文件体积较小
  • 运行速度快
  • 适合生产环境
编译时间对比示例
# 测量编译时间
time cargo build
time cargo build --release

# 清理构建缓存后重新编译
cargo clean
time cargo build

增量编译

Cargo 默认启用增量编译,只重新编译修改的部分:

# 首次编译(较慢)
cargo build

# 修改代码后再次编译(快很多)
cargo build

配置增量编译(在 Cargo.toml 中):

[profile.dev]
incremental = true

[profile.release]
incremental = false  # release 通常禁用增量编译以获得更好的优化

并行编译

Cargo 自动并行编译多个 crate:

# 指定并行任务数
cargo build -j 4

# 使用所有 CPU 核心
cargo build -j $(nproc)  # Linux
cargo build -j $(sysctl -n hw.ncpu)  # macOS

Cargo 项目管理

依赖管理

添加依赖

Cargo.toml[dependencies] 部分添加:

[dependencies]
serde = "1.0"                           # 指定版本
serde_json = "1.0.100"                  # 精确版本
rand = "0.8.5"                          # 语义化版本
tokio = { version = "1.0", features = ["full"] }  # 带特性
regex = { git = "https://github.com/rust-lang/regex" }  # Git 仓库
my_local_crate = { path = "../my_local_crate" }  # 本地路径
版本规则
[dependencies]
# 版本规则说明
crate1 = "1.2.3"      # 相当于 ^1.2.3,允许 >=1.2.3 且 <2.0.0
crate2 = "^1.2.3"     # 允许 >=1.2.3 且 <2.0.0
crate3 = "~1.2.3"     # 允许 >=1.2.3 且 <1.3.0
crate4 = ">=1.2.3"    # 任何 >=1.2.3 的版本
crate5 = "1.2.*"      # 1.2.x 系列
crate6 = "*"          # 任意版本(不推荐)
更新依赖
# 更新依赖到最新兼容版本
cargo update

# 更新特定依赖
cargo update -p serde

# 查看过时的依赖
cargo outdated  # 需要安装:cargo install cargo-outdated
查看依赖树
# 查看依赖树
cargo tree

# 查看特定依赖的依赖
cargo tree -p serde

# 只显示直接依赖
cargo tree --depth 1

# 显示重复的依赖
cargo tree --duplicates

工作空间

工作空间可以管理多个相关的包。

创建工作空间

项目结构:

my_workspace/
├── Cargo.toml          # 工作空间配置
├── crate1/
│   ├── Cargo.toml
│   └── src/
├── crate2/
│   ├── Cargo.toml
│   └── src/
└── target/             # 共享的构建目录

根目录 Cargo.toml:

[workspace]
members = [
    "crate1",
    "crate2",
]

[workspace.dependencies]
# 工作空间共享依赖
serde = "1.0"

成员 crate 可以引用共享依赖:

[dependencies]
serde = { workspace = true }
工作空间命令
# 构建整个工作空间
cargo build

# 构建特定成员
cargo build -p crate1

# 运行特定成员的二进制
cargo run -p crate1

# 测试整个工作空间
cargo test

# 测试特定成员
cargo test -p crate2

特性标志

特性(features)允许条件编译代码。

定义特性

Cargo.toml:

[features]
default = ["feature1"]          # 默认启用的特性
feature1 = []                   # 简单特性
feature2 = ["dep:serde"]        # 启用可选依赖
full = ["feature1", "feature2"] # 组合特性

[dependencies]
serde = { version = "1.0", optional = true }
使用特性

代码中:

#[cfg(feature = "feature1")]
fn feature1_function() {
    println!("Feature 1 is enabled");
}

#[cfg(not(feature = "feature1"))]
fn feature1_function() {
    println!("Feature 1 is disabled");
}

编译时:

# 使用默认特性
cargo build

# 不使用默认特性
cargo build --no-default-features

# 指定特性
cargo build --features feature1

# 指定多个特性
cargo build --features "feature1,feature2"

# 使用所有特性
cargo build --all-features

构建优化

优化配置文件

Cargo.toml:

# Debug 配置(开发)
[profile.dev]
opt-level = 0          # 无优化
debug = true           # 包含调试信息
split-debuginfo = "..."  # 调试信息分割
debug-assertions = true
overflow-checks = true
lto = false
panic = 'unwind'
incremental = true
codegen-units = 256    # 并行代码生成单元

# Release 配置(生产)
[profile.release]
opt-level = 3          # 最大优化
debug = false
split-debuginfo = "..."
debug-assertions = false
overflow-checks = false
lto = true             # 链接时优化
panic = 'abort'        # 崩溃时直接退出
incremental = false
codegen-units = 1      # 单个代码生成单元,更好的优化

# 自定义 profile
[profile.release-with-debug]
inherits = "release"
debug = true           # Release 优化但保留调试信息

优化级别详解

[profile.release]
# opt-level 可选值:
# 0 - 无优化(最快编译)
# 1 - 基本优化
# 2 - 一些优化
# 3 - 全部优化(最慢编译,最快运行)
# "s" - 优化大小
# "z" - 更激进的大小优化
opt-level = 3

LTO(链接时优化)

[profile.release]
# lto 可选值:
# false - 禁用 LTO
# true 或 "fat" - 完整 LTO(最慢,最优)
# "thin" - ThinLTO(折中方案)
lto = true

减小二进制大小

[profile.release]
opt-level = "z"        # 优化大小
lto = true
codegen-units = 1
strip = true           # 自动剥离符号(Rust 1.59+)
panic = "abort"        # 移除展开代码

额外工具:

# 使用 UPX 压缩(可能影响启动速度)
upx --best --lzma target/release/my_project

# 查看二进制大小分析
cargo install cargo-bloat
cargo bloat --release

编译缓存

使用 sccache 加速重复编译:

# 安装 sccache
cargo install sccache

# 配置环境变量
export RUSTC_WRAPPER=sccache

# 查看缓存统计
sccache --show-stats

跨平台编译

安装目标平台

# 列出所有支持的目标
rustup target list

# 添加目标平台
rustup target add x86_64-unknown-linux-gnu
rustup target add x86_64-pc-windows-gnu
rustup target add x86_64-apple-darwin
rustup target add aarch64-unknown-linux-gnu
rustup target add wasm32-unknown-unknown

交叉编译

# 编译到指定目标
cargo build --target x86_64-unknown-linux-gnu

# Release 版本
cargo build --release --target x86_64-pc-windows-gnu

配置交叉编译工具链

~/.cargo/config.toml:

[target.x86_64-unknown-linux-gnu]
linker = "x86_64-linux-gnu-gcc"

[target.aarch64-unknown-linux-gnu]
linker = "aarch64-linux-gnu-gcc"

[target.x86_64-pc-windows-gnu]
linker = "x86_64-w64-mingw32-gcc"
ar = "x86_64-w64-mingw32-ar"

使用 cross 工具

cross 是一个零配置的交叉编译工具:

# 安装 cross
cargo install cross

# 使用 cross 替代 cargo
cross build --target aarch64-unknown-linux-gnu
cross build --target armv7-unknown-linux-gnueabihf

条件编译

#[cfg(target_os = "windows")]
fn platform_specific() {
    println!("Windows 平台");
}

#[cfg(target_os = "linux")]
fn platform_specific() {
    println!("Linux 平台");
}

#[cfg(target_os = "macos")]
fn platform_specific() {
    println!("macOS 平台");
}

#[cfg(target_arch = "x86_64")]
fn arch_specific() {
    println!("x86_64 架构");
}

#[cfg(target_arch = "aarch64")]
fn arch_specific() {
    println!("ARM64 架构");
}

打包和发布

生成可执行文件

单文件发布
# 编译 release 版本
cargo build --release

# 可执行文件位于
# Linux/macOS: target/release/my_project
# Windows: target\release\my_project.exe

# 测试可执行文件
./target/release/my_project
静态链接

在 Linux 上创建静态链接的二进制:

# 添加 musl 目标
rustup target add x86_64-unknown-linux-musl

# 编译
cargo build --release --target x86_64-unknown-linux-musl

# 生成的二进制不依赖 glibc
剥离调试符号
# 在 Linux/macOS 上使用 strip
strip target/release/my_project

# 或在 Cargo.toml 中配置
[profile.release]
strip = true

发布到 crates.io

准备工作
  1. 注册账号

    访问 crates.io 并使用 GitHub 账号登录。

  2. 获取 API Token

    在账号设置中生成 API token。

  3. 登录 Cargo

    cargo login
    # 粘贴你的 API token
    
完善 Cargo.toml
[package]
name = "my_awesome_crate"
version = "0.1.0"
edition = "2021"
authors = ["Your Name <you@example.com>"]
license = "MIT OR Apache-2.0"      # 开源许可证
description = "A short description of your crate"
homepage = "https://example.com"
repository = "https://github.com/username/repo"
documentation = "https://docs.rs/my_awesome_crate"
readme = "README.md"
keywords = ["example", "tutorial", "rust"]
categories = ["command-line-utilities"]

[dependencies]
# ...
发布前检查
# 检查包内容
cargo package --list

# 本地打包(不上传)
cargo package

# 测试打包后的 crate
cargo publish --dry-run

# 检查文档
cargo doc --open
发布
# 发布到 crates.io
cargo publish

# 发布后无法删除,但可以撤回(72小时内)
cargo yank --vers 0.1.0

# 取消撤回
cargo yank --vers 0.1.0 --undo
版本管理

遵循语义化版本:

  • 0.1.0 -> 0.1.1: 补丁版本(bug 修复)
  • 0.1.0 -> 0.2.0: 次版本(新功能,向后兼容)
  • 0.1.0 -> 1.0.0: 主版本(重大变更)
# 使用 cargo-release 自动化版本管理
cargo install cargo-release
cargo release patch  # 0.1.0 -> 0.1.1
cargo release minor  # 0.1.0 -> 0.2.0
cargo release major  # 0.1.0 -> 1.0.0

创建安装包

使用 cargo-deb(Debian/Ubuntu)
# 安装
cargo install cargo-deb

# 在 Cargo.toml 中配置
[package.metadata.deb]
maintainer = "Your Name <you@example.com>"
copyright = "2024, Your Name <you@example.com>"
depends = "$auto"
section = "utility"
priority = "optional"
assets = [
    ["target/release/my_project", "usr/bin/", "755"],
    ["README.md", "usr/share/doc/my_project/", "644"],
]

# 生成 .deb 包
cargo deb

# 输出在 target/debian/my_project_0.1.0_amd64.deb
使用 cargo-generate-rpm(RedHat/Fedora)
# 安装
cargo install cargo-generate-rpm

# 生成 .rpm 包
cargo build --release
strip -s target/release/my_project
cargo generate-rpm

# 输出在 target/generate-rpm/my_project-0.1.0-1.x86_64.rpm
使用 cargo-bundle(macOS/Windows)
# 安装
cargo install cargo-bundle

# 在 Cargo.toml 中配置
[package.metadata.bundle]
name = "My Application"
identifier = "com.example.my-application"
icon = ["icon.icns"]
version = "0.1.0"
copyright = "Copyright (c) 2024"
category = "Developer Tool"

# macOS 生成 .app 包
cargo bundle --release

# Windows 生成 .exe(需要额外配置)
使用 WiX(Windows MSI)

创建 wix/main.wxs:

<?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
  <Product
    Id="*"
    Name="My Application"
    Language="1033"
    Version="0.1.0"
    Manufacturer="Your Company"
    UpgradeCode="PUT-GUID-HERE">

    <Package InstallerVersion="200" Compressed="yes" />

    <Media Id="1" Cabinet="media1.cab" EmbedCab="yes" />

    <Directory Id="TARGETDIR" Name="SourceDir">
      <Directory Id="ProgramFilesFolder">
        <Directory Id="INSTALLFOLDER" Name="MyApp" />
      </Directory>
    </Directory>

    <Component Id="MainExecutable" Guid="PUT-GUID-HERE" Directory="INSTALLFOLDER">
      <File Id="MyAppExe" Source="../target/release/my_project.exe" KeyPath="yes" />
    </Component>

    <Feature Id="MainFeature" Title="Main Feature" Level="1">
      <ComponentRef Id="MainExecutable" />
    </Feature>
  </Product>
</Wix>

使用 cargo-wix:

cargo install cargo-wix
cargo wix init
cargo wix
Docker 容器

创建 Dockerfile:

# 构建阶段
FROM rust:1.75 as builder
WORKDIR /usr/src/app
COPY . .
RUN cargo build --release

# 运行阶段
FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y \
    ca-certificates \
    && rm -rf /var/lib/apt/lists/*
COPY --from=builder /usr/src/app/target/release/my_project /usr/local/bin/my_project
CMD ["my_project"]

使用多阶段构建减小镜像:

FROM rust:1.75 as builder
WORKDIR /app
COPY Cargo.* ./
RUN mkdir src && echo "fn main() {}" > src/main.rs && cargo build --release && rm -rf src

COPY src ./src
RUN cargo build --release

FROM gcr.io/distroless/cc-debian12
COPY --from=builder /app/target/release/my_project /
CMD ["/my_project"]

构建和运行:

docker build -t my_project:latest .
docker run my_project:latest

常见问题和最佳实践

编译速度优化

  1. 使用更快的链接器

~/.cargo/config.toml:

# Linux
[target.x86_64-unknown-linux-gnu]
rustflags = ["-C", "link-arg=-fuse-ld=lld"]

# macOS
[target.x86_64-apple-darwin]
rustflags = ["-C", "link-arg=-fuse-ld=lld"]

# Windows
[target.x86_64-pc-windows-msvc]
rustflags = ["-C", "link-arg=/INCREMENTAL"]

安装 lld:

# Ubuntu/Debian
sudo apt install lld

# macOS
brew install llvm

# Fedora
sudo dnf install lld
  1. 使用 cargo-watch 自动编译
cargo install cargo-watch
cargo watch -x check
cargo watch -x run
cargo watch -x "test --lib"
  1. 使用 mold 链接器(Linux,最快)
# 安装 mold
sudo apt install mold  # Ubuntu 22.04+
# 或从源码编译

# 配置
[target.x86_64-unknown-linux-gnu]
rustflags = ["-C", "link-arg=-fuse-ld=mold"]

依赖管理最佳实践

  1. 使用 cargo-edit 管理依赖
cargo install cargo-edit

# 添加依赖
cargo add serde

# 添加开发依赖
cargo add --dev proptest

# 添加带特性的依赖
cargo add tokio --features full

# 移除依赖
cargo rm serde

# 更新到特定版本
cargo upgrade serde@1.0.100
  1. 定期审计依赖安全性
cargo install cargo-audit
cargo audit

# 修复已知漏洞
cargo audit fix
  1. 检查许可证合规
cargo install cargo-license
cargo license

# 生成许可证报告
cargo license --json > licenses.json

代码质量工具

  1. Rustfmt - 代码格式化
# 格式化代码
cargo fmt

# 检查格式(CI 中使用)
cargo fmt -- --check

# 配置 rustfmt.toml
max_width = 100
tab_spaces = 4
edition = "2021"
  1. Clippy - Lint 工具
# 运行 clippy
cargo clippy

# 将警告视为错误
cargo clippy -- -D warnings

# 修复建议(实验性)
cargo clippy --fix
  1. 测试覆盖率
# 使用 tarpaulin
cargo install cargo-tarpaulin
cargo tarpaulin --out Html

# 使用 llvm-cov(推荐)
cargo install cargo-llvm-cov
cargo llvm-cov --html

CI/CD 配置示例

.github/workflows/ci.yml:

name: CI

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: dtolnay/rust-toolchain@stable
      - uses: Swatinem/rust-cache@v2

      - name: Check formatting
        run: cargo fmt -- --check

      - name: Clippy
        run: cargo clippy -- -D warnings

      - name: Run tests
        run: cargo test --all-features

      - name: Build release
        run: cargo build --release

  coverage:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: dtolnay/rust-toolchain@stable
      - name: Install cargo-llvm-cov
        run: cargo install cargo-llvm-cov
      - name: Generate coverage
        run: cargo llvm-cov --all-features --lcov --output-path lcov.info
      - name: Upload to codecov
        uses: codecov/codecov-action@v3
        with:
          files: lcov.info

性能分析

  1. 基准测试

创建 benches/benchmark.rs:

use criterion::{black_box, criterion_group, criterion_main, Criterion};

fn fibonacci(n: u64) -> u64 {
    match n {
        0 => 1,
        1 => 1,
        n => fibonacci(n-1) + fibonacci(n-2),
    }
}

fn criterion_benchmark(c: &mut Criterion) {
    c.bench_function("fib 20", |b| b.iter(|| fibonacci(black_box(20))));
}

criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);

Cargo.toml:

[dev-dependencies]
criterion = "0.5"

[[bench]]
name = "benchmark"
harness = false

运行:

cargo bench
  1. 性能分析工具
# flamegraph
cargo install flamegraph
cargo flamegraph

# perf(Linux)
perf record -g target/release/my_project
perf report

常见错误解决

  1. 链接错误

    • 确保安装了必要的系统库
    • 检查交叉编译工具链
    • 使用 --verbose 查看详细错误
  2. 依赖冲突

    cargo tree --duplicates
    cargo update
    
  3. 编译缓存问题

    cargo clean
    rm -rf ~/.cargo/registry/cache
    
  4. 内存不足

    # 减少并行度
    cargo build -j 1
    
    # 或配置
    [build]
    jobs = 1
    

总结

本文详细介绍了 Rust 从安装到打包发布的完整流程:

  1. 安装: 使用 rustup 在各平台安装 Rust
  2. 工具链: 管理多版本工具链和组件
  3. 编译: 使用 rustc 和 cargo 编译项目
  4. 优化: 配置 profile 优化性能和大小
  5. 跨平台: 交叉编译到不同平台
  6. 打包: 生成各平台安装包
  7. 发布: 发布到 crates.io 或分发二进制

掌握这些内容后,你就可以高效地开发、编译和发布 Rust 项目了!

推荐资源

祝你 Rust 学习愉快!


Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐