rust-fundamentals
Skill0 starsChanged 36 days agoMITView on GitHub
Use when learning or reviewing Rust language basics.
1 other project uses a version of this.
Adopted by
Most recently taken up by
- bkywksj/knowledge-basetheir own version, first seen Oct 8, 2026
Other versions1 project uses a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 1
- bkywksj/knowledge-base★ 340same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository15 other files it gives its agents.
- AGENTS.mdAGENTS.md
- rustoriaSkill
- rust-debuggingSkill
- rust-dependenciesSkill
- rust-axumSkill
- rust-clapSkill
- rust-dieselSkill
- rust-ratatuiSkill
- rust-rayonSkill
- rust-serdeSkill
- rust-tokioSkill
- rust-productionSkill
- rust-code-auditSkill
- rust-stdSkill
- rust-unsafe-checkerSkill
The file
We split this skill into the rules it gives an agent
5 rules. About 0 are common, 2 are distinctive, and 3 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
3
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 20
Ownership: every value has exactly one owner.
- Very specific: line 41
Prefer let bindings; use mut only when needed.
- Distinctive: line 184
Use concrete analogies for ownership (a toy: one owner, lending = borrowing, giving = moving) — then show the compiler enforcing it.
- Very specific: line 188
Use dbg!(&value) to inspect values at runtime.
- Very specific: line 195
No blocking in async; no casual unwrap() in production paths.
≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
rust-fundamentals — The Rust Language
Canonical native-Rust foundation. Reference-oriented: concise rules, small correct examples, decision guidance. For deep
dives see references/ownership.md, references/borrowing.md, references/type-design.md.
When to use
- Learning or reviewing Rust from zero (variables through traits and generics).
- Teaching or explaining Rust to others (see Pedagogy below).
- Reviewing code for language-level correctness.
- Answering "which language feature fits this?" questions.
Core rules
- Ownership: every value has exactly one owner; when the owner goes out of scope, the value is dropped. Moving a value transfers ownership; the original binding is invalid.
- Borrowing:
&Tshared borrows (any number) XOR&mut Texclusive borrow (one at a time) — never both live at once. Borrows must not outlive the referent. - Copy vs Clone:
Copytypes (integers, bools, chars, references, tuples/arrays of Copy) duplicate implicitly on assignment.Cloneis explicit (.clone()) and may be expensive.Copyrequires all fieldsCopyand noDropimpl;Box<T>is neverCopy. - Lifetimes: describe how long references are valid. Elision covers most cases; annotate when the compiler cannot
infer.
T: 'staticmeans no non-'staticborrows inside (a&'static strsatisfies it).
Language tour
Variables, mutability, constants, statics
let x = 5; // immutable by default
let mut y = 5; // mutable
const MAX: u32 = 100; // compile-time constant, must be typed
static NAME: &str = "app"; // 'static lifetime, single location- Prefer
letbindings; usemutonly when needed. constfor compile-time values;staticfor global state (rare;static mutis unsafe and restricted in edition 2024 — use atomics orOnceLockinstead).- Shadowing (
let x = ...; let x = ...) is idiomatic for transformations.
Functions, closures, expressions
fn add(x: i32, y: i32) -> i32 { x + y } // last expression is the return value
let f = |x: i32| x * 2; // closure
let v = { let a = 1; a + 2 }; // block is an expression- Functions: parameters typed,
->return type, no semicolon on the returned expression. - Closures:
|args| body; capture by reference by default,moveto take ownership. if/matchare expressions — they return values. Statements end with;.
Control flow
if/else if/else,match(exhaustive — compiler enforces all arms),if let/while letfor single-pattern binding.- Loops:
loop(withbreak value),while,for x in iter(idiomatic iteration; arrays are directly iterable — no.iter()needed on array literals). ?propagates errors in functions returningOptionorResult;fn main() -> Result<(), E: Debug>is stable.
Structs, enums, pattern matching
struct User { name: String, age: u32 } // named fields
struct Point(i32, i32); // tuple struct
struct Unit; // unit struct (marker)
enum Shape { Circle(f64), Rect(f64, f64) } // variants carry data- Enums are the primary tool for modeling state; make invalid states unrepresentable (typestate pattern — see type-design reference).
matchon enums must be exhaustive; use_only when truly ignoring.- Destructuring:
letonly takes irrefutable patterns (structs, tuples, single-variant enums) - refutable patterns likeShape::Circle(r)on a multi-variant enum needif let Shape::Circle(r) = s { .. }ormatch.
Generics, traits, associated types
fn largest<T: PartialOrd>(list: &[T]) -> &T { /* ... */ }
trait Summary { fn summarize(&self) -> String; }
fn notify(item: &impl Summary) { /* static dispatch */ }
fn notify_dyn(item: &dyn Summary) { /* dynamic dispatch */ }- Trait bounds:
T: Trait, multiple with+,whereclauses for complex bounds. impl Traitin argument position (static dispatch) vsdyn Trait(dynamic dispatch, object safety required — traits with generic methods orSelfreturns are not dyn-compatible).- Associated types vs generics: associated type when each impl has one natural type; generic parameter when callers choose.
Selfrefers to the implementing type;Self: Sizedbound allows sized methods on dyn-unsafe traits.
Lifetimes, ownership, borrowing, moves
let s = String::from("hi");
let s2 = s; // move — s is invalid now
let n = 5; let n2 = n; // Copy — n still valid
let r = &s2; // borrow- Return owned data from functions; return references only to data that outlives the call (parameters,
&self,'static). - E0515 (returning a reference to a local): return an owned value, or a genuine
static, or (rarely)Box::leak. &Stringas a parameter is an anti-pattern — take&str(clippyptr_arg).- Raw pointers (
*const T,*mut T) are for FFI/unsafe only; creating them is safe, dereferencing is not.
References, slices, String, str
&T/&mut T— references;&[T]— slice (borrowed view);str— UTF-8 string slice.Stringis owned UTF-8;&stris a borrowed view. Pass&str, returnString.- Slices:
&v[1..3],&v[..],&v[2..]; panics on out-of-bounds or non-char-boundary. String↔&str:&s(deref coercion),s.as_str(),String::from("x"),"x".to_string().
Iterators
- Lazy: nothing runs until a consuming call. Chain
map/filter/flat_map/filter_mapwithout intermediatecollect(). for x in vconsumesVec;for x in &vborrows;for x in v.iter()is explicit borrowing.- Collect into
Vec,String,HashMap,Result<Vec<_>, E>(fail-fast),Option<Vec<_>>. - See
rust-stdfor the full combinator map.
Type aliases, newtypes, DSTs, dyn, impl Trait, Self, where
type Meters = f64;— alias (no new type).struct Meters(f64);— newtype (new type, zero cost, enforces units).- DSTs (
str,[T],dyn Trait) are unsized — always behind a pointer (&str,Box<dyn Trait>). dyn Trait= trait object (dynamic dispatch);impl Trait= opaque concrete type (static dispatch).where T: Trait + Sendkeeps signatures readable.
Macros, attributes, derive, cfg
println!,vec!,format!— declarative/stdlib macros;macro_rules!for simple metaprogramming; proc macros (#[derive(...)]) for code generation.- Attributes:
#[derive(Debug, Clone, PartialEq)],#[test],#[cfg(test)],#[allow(...)],#[inline],#[must_use]. #[cfg(feature = "x")]/cfg!for conditional compilation;#[cfg_attr].- Derives:
Debug,Clone,Copy,PartialEq/Eq,PartialOrd/Ord,Hash,Default,Serialize/Deserialize(serde).
Advanced concepts
Drop, Deref, DerefMut
Drop::dropruns when a value goes out of scope. Drop order: locals in reverse declaration order; struct fields in declaration order; tuple/array elements in order; parameters after the body; closure captures in capture order.ManuallyDrop<T>suppresses drop (for unsafe transfers);mem::forgetleaks (safe but usually wrong).Deref/DerefMutare for smart pointers (Box, Rc, Arc, Cow) — not for newtypes. PreferAsRefor an explicit accessor for newtypes.
Conversion traits
Implement From (not Into — it comes free). TryFrom/TryInto for fallible conversions. AsRef for
borrow-generic parameters. Borrow for hash-map key equivalence. FromStr for parsing. Display for user output,
Debug for diagnostics. See rust-std for the full table.
Operator traits, indexing, formatting
std::ops:Add,Sub,Index/IndexMut- operator and indexing traits; implement where the operation is meaningful for domain types. (PartialEq/Eq/PartialOrd/Ordlive instd::cmp, notstd::ops.){}usesDisplay;{:?}usesDebug;{:#?}pretty-prints;{:x?}hex.write!/writeln!to anyfmt::Write(String, files, buffers).
Allocation and layout
- Stack: fast, fixed size, scoped. Heap:
Box,Vec,String— flexible, owned, freed on drop. Box<T>for heap allocation, recursive types, large moves, trait objects.repr(C)for FFI/ABI layout; defaultrepr(Rust)lets rustc reorder fields for padding (manual field ordering matters mainly forrepr(C)and cache-line layout).size_of::<T>(),align_of::<T>()for layout questions.
Common compiler errors
| Error | Meaning | Fix |
| E0384 | cannot assign twice to immutable | add mut or shadow |
| E0507 | cannot move out of borrowed content | clone, borrow, or restructure |
| E0515 | cannot return reference to local | return owned / static / Box::leak |
| E0597 | borrow does not live long enough | shorten borrow, extend data lifetime, or own the data |
| E0308 | mismatched types | check types, deref coercion, or convert |
| E0432 | unresolved import | check use path and module visibility |
| E0433 | failed to resolve: undeclared crate or module | add the dependency, fix the path, check module visibility |
Pedagogy (teaching or explaining Rust)
- Use concrete analogies for ownership (a toy: one owner, lending = borrowing, giving = moving) — then show the compiler enforcing it.
- Show real compiler errors and fix them live; the compiler is the best teacher.
- Build incrementally: one concept per step; run
cargo runoften. - Use
dbg!(&value)to inspect values at runtime. - Draw ownership/borrow diagrams for non-obvious cases.
- Relate new concepts to what the learner already knows, then show where Rust differs.
House rules
- Native first:
stdbefore crates (seerust-std). - No blocking in async; no casual
unwrap()in production paths. - Version-sensitive advice names its version.
- Examples in this repository use edition 2021.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

