Ubuntu 上优化 Rust 环境的实用清单
一 基础安装与镜像加速
# 1) 设置镜像(可选,提升下载速度)
export RUSTUP_DIST_SERVER=https://mirrors.ustc.edu.cn/rust-static
export RUSTUP_UPDATE_ROOT=https://mirrors.ustc.edu.cn/rust-static/rustup
# 2) 安装 rustup(若已安装可跳过)
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
# 3) 使环境变量立即生效
source "$HOME/.cargo/env"
# 4) 验证
rustc -V && cargo -V
rustup show
mkdir -p ~/.cargo
cat > ~/.cargo/config <<'EOF'
[source.crates-io]
replace-with = 'ustc'
[source.ustc]
registry = "sparse+https://mirrors.ustc.edu.cn/crates.io-index/"
[net]
git-fetch-with-cli = true
EOF
rustup update
rustup default stable # 或 nightly / beta
rustup check # 检查更新
rustup doc # 本地离线文档
以上做法可确保工具链为最新、可多版本共存,并显著提升国内网络环境下的安装与依赖下载体验。二 构建性能与产物优化
cargo build --release
[profile.release]
lto = true
codegen-units = 1
opt-level = "z" # 或 "s":更小体积;"3":更高性能(默认)
cargo install cargo-binstall
cargo binstall cargo-audit cargo-outdated cargo-tree
cargo clean
# 结合构建缓存目录共享(如 sccache / direnv)进一步提升多项目构建效率
通过 Release 模式与 LTO 等优化,可显著改善最终二进制体的性能与体积表现。三 交叉编译与系统依赖
sudo apt-get update
sudo apt-get install -y build-essential libssl-dev pkg-config clang
# 安装交叉编译器
sudo apt-get install -y gcc-arm-linux-gnueabihf
# 添加目标
rustup target add armv7-unknown-linux-gnueabihf
# 配置链接器
mkdir -p ~/.cargo
cat >> ~/.cargo/config <<'EOF'
[target.armv7-unknown-linux-gnueabihf]
linker = "arm-linux-gnueabihf-gcc"
EOF
# 构建
cargo build --release --target armv7-unknown-linux-gnueabihf
四 日常维护与常见问题处理
source "$HOME/.cargo/env";为持久化,将 source "$HOME/.cargo/env" 加入 ~/.bashrc 或 ~/.zshrc。rustup update、rustup default stable|nightly 与 rustup show 管理多版本;如需回退或隔离项目工具链,可在项目根目录使用 rustup override。cargo tree 排查;清理构建缓存用 cargo clean;必要时删除 target/ 目录后重构建。chmod +x <binary> 添加执行权限。