Rustc Basics

mohitmishra786/low-level-dev-skills/skills/rust/rustc-basics

作者 mohitmishra786bdc58472fa9f无许可证253 个星标收录于 2026年10月9日更新于 2026年10月9日仓库3个月前更新

Rust compiler skill for systems programming. Use when selecting RUSTFLAGS, configuring Cargo profiles, tuning release builds, reading assembly or MIR output, understanding monomorphization, or diagnosing compilation errors. Activates on queries about rustc flags, Cargo.toml profiles, opt-level, LTO, codegen-units, target-cpu, emit asm, MIR, or Rust build performance.

AI 生成的概览

指导 Rust 编译器配置:RUSTFLAGS、Cargo 配置文件、构建调优,以及查看 MIR 或汇编输出。

功能
提供调用 Rust 编译器的操作说明,包括选择构建模式、配置 Cargo.toml 的 release 与 dev 配置文件,以及设置 RUSTFLAGS。内容涵盖查看汇编、MIR 与 LLVM IR 输出、理解单态化、缩减二进制体积,以及排查常见编译错误。文中还引用了一份关于 RUSTFLAGS 与 Cargo 配置文件模式的配套文档。
适用场景
适用于选择 RUSTFLAGS、调优 release 构建、配置 Cargo 配置文件或诊断 Rust 编译错误时。也适用于阅读汇编或 MIR 输出、研究单态化或缩减 Rust 二进制体积的场景。
运行要求
不含脚本,仅为说明性内容。执行所述命令需要 Rust 工具链(cargo、rustc)。部分可选步骤涉及第三方 cargo 子命令,如 cargo-show-asm、cargo-llvm-lines 和 cargo-bloat,需另行安装。

rustc Basics

Purpose

Guide agents through Rust compiler invocation: RUSTFLAGS, Cargo profile configuration, build modes, MIR and assembly inspection, monomorphization, and common compilation error patterns.

Triggers

  • "How do I configure a release build in Rust for maximum performance?"
  • "How do I see the assembly output for a Rust function?"
  • "What is monomorphization and why is it making my compile slow?"
  • "How do I enable LTO in Rust?"
  • "My Rust binary is too large — how do I shrink it?"
  • "How do I read Rust MIR output?"

Workflow

1. Choose a build mode

bash
# Debug (default) — fast compile, no optimization, debug infocargo build
# Release — optimized, no debug info by defaultcargo build --release
# Check only (fastest, no codegen)cargo check
# Build for specific targetcargo build --release --target aarch64-unknown-linux-gnu

2. Cargo.toml profile configuration

toml
[profile.release]opt-level = 3          # 0-3, "s" (size), "z" (aggressive size)debug = false          # true = full, 1 = line tables only, 0 = nonelto = "thin"           # false | "thin" | true (fat LTO)codegen-units = 1      # 1 = max optimization, higher = faster compilepanic = "abort"        # "unwind" (default) | "abort" (smaller binary)strip = "symbols"      # "none" | "debuginfo" | "symbols"overflow-checks = false # default true in debug, false in release
[profile.release-with-debug]inherits = "release"debug = true           # release build with debug symbolsstrip = "none"
[profile.dev]opt-level = 1          # Speed up debug builds slightly
SettingImpact
lto = true (fat)Best optimization, slowest link
lto = "thin"Good optimization, parallel link
codegen-units = 1Best inlining, slower compile
panic = "abort"Removes unwind tables, smaller binary
opt-level = "z"Aggressive size reduction

3. RUSTFLAGS

bash
# Set for a single buildRUSTFLAGS="-C target-cpu=native" cargo build --release
# Enable all target CPU featuresRUSTFLAGS="-C target-cpu=native -C target-feature=+avx2,+bmi2" cargo build --release
# Control codegen at invocation levelRUSTFLAGS="-C opt-level=3 -C codegen-units=1 -C lto=on" cargo build --release

Persistent in .cargo/config.toml:

toml
[build]rustflags = ["-C", "target-cpu=native"]
[target.x86_64-unknown-linux-gnu]rustflags = ["-C", "target-cpu=native", "-C", "link-arg=-fuse-ld=lld"]

4. Inspect assembly output

bash
# Using cargo-show-asm (recommended)cargo install cargo-show-asmcargo asm --release 'myapp::module::function_name'
# Using rustc directlyrustc --emit=asm -C opt-level=3 -C target-cpu=native src/lib.rscat lib.s
# View MIR (mid-level IR, before codegen)rustc --emit=mir -C opt-level=3 src/lib.rscat lib.mir
# View LLVM IRrustc --emit=llvm-ir -C opt-level=3 src/lib.rscat lib.ll
# Use Compiler Explorer (Godbolt) patterns locallyRUSTFLAGS="--emit=asm" cargo build --releasefind target/ -name "*.s"

5. Understand monomorphization

Rust generics are monomorphized — each concrete type instantiation produces separate code. This causes:

  • Binary size bloat
  • Longer compile times
  • Potential i-cache pressure
bash
# Measure monomorphization bloatcargo install cargo-llvm-linescargo llvm-lines --release | head -30
# Shows: lines of LLVM IR per function (monomorphized copies visible)

Mitigation strategies:

rust
// 1. Type erasure with dyn Trait (trades monomorphization for dispatch)fn process(iter: &mut dyn Iterator<Item = i32>) { ... }
// 2. Non-generic inner function patternfn my_generic<T: AsRef<str>>(s: T) {    fn inner(s: &str) { /* actual work */ }    inner(s.as_ref())  // monomorphization only in thin wrapper}

6. Binary size reduction

toml
[profile.release]opt-level = "z"lto = truecodegen-units = 1panic = "abort"strip = "symbols"
bash
# Check binary size breakdowncargo install cargo-bloatcargo bloat --release --crates      # per-crate sizecargo bloat --release -n 20         # top 20 largest functions
# Compress executable (at cost of startup time)upx --best --lzma target/release/myapp

7. Common error triage

ErrorCauseFix
cannot find function in this scopeMissing use or wrong module pathAdd use crate::module::fn_name
the trait X is not implemented for YMissing impl or wrong generic boundImplement trait or adjust bounds
lifetime may not live long enoughBorrow checker lifetime issueAdd explicit lifetime annotations
cannot borrow as mutable because also borrowed as immutableAliasing violationRestructure borrows to not overlap
use of moved valueValue used after move into closure or functionUse .clone() or borrow instead
mismatched types: expected &str found StringString vs &str confusionUse .as_str() or &my_string

8. Useful rustc flags

bash
# Show all enabled features at a given opt levelrustc -C opt-level=3 --print cfg
# List available targetsrustc --print target-list
# Show target-specific featuresrustc --print target-features --target x86_64-unknown-linux-gnu
# Explain an error coderustc --explain E0382

For RUSTFLAGS reference and Cargo profile patterns, see references/rustflags-profiles.md [blocked].

Related skills

  • Use skills/rust/cargo-workflows for workspace management and Cargo tooling
  • Use skills/rust/rust-debugging for debugging Rust binaries with GDB/LLDB
  • Use skills/rust/rust-profiling for profiling and flamegraphs
  • Use skills/rust/rust-sanitizers-miri for memory safety validation

来源与署名

来源:mohitmishra786/low-level-dev-skills位于skills/rust/rustc-basics提交bdc5847

许可证: 无许可证

内容归原作者所有。SourceWeft 从公开仓库中收录这些内容。

举报或申请下架