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 從公開儲存庫中收錄這些內容。

檢舉或申請下架