Rustc Basics

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

by mohitmishra786bdc58472fa9fNo license253 starsListed Oct 9, 2026Updated Oct 9, 2026Repository updated 3 months ago

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-generated overview

Guides Rust compiler configuration: RUSTFLAGS, Cargo profiles, build tuning, and inspecting MIR or assembly output.

What it does
Provides instructions for invoking the Rust compiler, including choosing build modes, configuring Cargo.toml release and dev profiles, and setting RUSTFLAGS. It covers inspecting assembly, MIR, and LLVM IR output, understanding monomorphization, reducing binary size, and triaging common compilation errors. It also references a companion document on RUSTFLAGS and Cargo profile patterns.
When to use it
Use when selecting RUSTFLAGS, tuning release builds, configuring Cargo profiles, or diagnosing Rust compilation errors. Also relevant when reading assembly or MIR output, investigating monomorphization, or shrinking a Rust binary.
Requirements
No scripts; instructions only. Requires a Rust toolchain (cargo, rustc) for the described commands. Some optional steps reference third-party cargo subcommands such as cargo-show-asm, cargo-llvm-lines, and cargo-bloat, which must be installed separately.

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

Source and attribution

Source:mohitmishra786/low-level-dev-skillsinskills/rust/rustc-basicsat commitbdc5847

License: No license

Content belongs to its original authors. SourceWeft indexes it from a public repository.

Report or request removal