قابل تلاش، قابل پرنٹ Rust حوالہ: اونرشپ اور بارونگ، ٹریٹس، پیٹرن میچنگ، Option اور Result، اٹریٹرز اور Cargo۔ مفت۔

Basics

10
let x = 5;
Immutable binding (default)
let mut count = 0; count += 1;
Mutable binding
let x = "5"; let x: i32 = x.parse()?;
Shadowing (new type allowed)
i32, u64, f64, bool, char, usize
Core scalar types
let t = (1, "a"); t.0
Tuple + field access
let a = [0u8; 16];
Fixed array of 16 zeros
const MAX_USERS: u32 = 100;
Compile-time constant
let n = big as u8;
Explicit numeric cast
let s: String; let sl: &str;
Owned string vs string slice
println!("{name} has {count}");
Inline variable interpolation

Ownership, borrowing & lifetimes

10
let b = a; // a is moved
Assignment moves non-Copy types
let b = a.clone();
Deep copy keeps both usable
fn read(s: &String) / read(&s)
Shared borrow (many allowed)
fn edit(s: &mut String) / edit(&mut s)
Exclusive borrow (only one)
// no &mut while & borrows live
The core borrow rule
fn greet(name: &str)
Prefer &str params over &String
i32, bool, char, &T are Copy
Copy types never move
fn first<'a>(a: &'a str, b: &str) -> &'a str
Tie output to an input lifetime
struct View<'a> { text: &'a str }
Struct holding a reference
let s: &'static str = "literal";
Lives for the whole program

Structs, enums & impl

10
struct User { name: String, age: u32 }
Struct definition
let u = User { name, age: 30 };
Literal + field-init shorthand
let u2 = User { age: 31, ..u };
Struct update syntax
struct Meters(f64);
Tuple struct (newtype idiom)
impl User { fn new(name: String) -> Self { ... } }
Associated constructor
fn label(&self) -> String
Method borrowing self
fn rename(&mut self, n: String)
Method mutating self
enum Shape { Circle(f64), Rect { w: f64, h: f64 } }
Enum with data per variant
#[derive(Debug, Clone, PartialEq)]
Auto-implement common traits
let cfg = Config::default();
Default trait construction

Pattern matching

10
match n { 0 => "zero", _ => "other" }
Exhaustive match expression
match shape { Shape::Circle(r) => ... }
Destructure enum variants
match n { 1..=5 => "low", _ => "high" }
Range patterns
match p { Point { x, y: 0 } => ... }
Destructure struct fields
Some(n) if n > 10 => "big"
Match guard
id @ 1..=9 => use(id)
Bind while matching (@)
if let Some(v) = opt { use(v); }
Match a single pattern
let Some(v) = opt else { return; };
let-else early exit
while let Some(x) = stack.pop() { ... }
Loop while a pattern holds
matches!(status, Status::Active)
Boolean pattern test macro

Option & Result

12
let opt: Option<i32> = Some(5);
Maybe-a-value type
let res: Result<T, E> = Ok(v);
Success-or-error type
let v = load()?;
? propagates None / Err up
opt.unwrap_or(0)
Value or a default
opt.unwrap_or_else(|| compute())
Lazy default
opt.unwrap_or_default()
Value or Default::default()
opt.map(|v| v * 2)
Transform if present
opt.and_then(|v| v.checked_mul(2))
Chain fallible steps (flatMap)
opt.ok_or(MyError::Missing)?
Option → Result
res.map_err(|e| AppError::Io(e))
Convert the error type
opt.is_some(); res.is_err();
Cheap state checks
let v = opt.take();
Move out, leave None behind

Traits & generics

11
trait Greet { fn hello(&self) -> String; }
Trait: shared behavior
trait Greet { fn wave(&self) { ... } }
Default method body
impl Greet for User { ... }
Implement for a type
fn welcome<T: Greet>(x: &T)
Generic with a trait bound
fn f<T>(x: T) where T: Greet + Clone
where clause for many bounds
fn welcome(x: &impl Greet)
impl Trait argument sugar
fn make() -> impl Iterator<Item = u32>
Opaque return type
let objs: Vec<Box<dyn Greet>> = ...;
Trait objects (dynamic dispatch)
impl From<u32> for Meters { ... }
From gives you Into for free
let m: Meters = 5u32.into();
Convert via Into
impl fmt::Display for User { ... }
Custom {} formatting

Collections

12
let mut v = vec![1, 2, 3];
Vec literal macro
v.push(4); v.pop();
Append / remove last
v.get(0) // Option<&T>
Safe indexing (v[9] panics)
for x in &v { ... }
Iterate by reference
v.sort(); v.sort_by_key(|u| u.age);
In-place sorting
v.retain(|x| *x > 0);
Keep matching elements
let mut m = HashMap::new(); m.insert(k, v);
Hash map basics
*counts.entry(word).or_insert(0) += 1;
Entry API counter idiom
m.contains_key(&k); m.get(&k);
Lookups return Option
s.push_str("more"); format!("{a}{b}")
Grow / build strings
s.chars().rev().collect::<String>()
Char-wise string processing
names.join(", ")
Join a Vec<String>

Iterators & closures

14
v.iter().map(|x| x * 2).collect::<Vec<_>>()
Transform and materialize
.filter(|x| **x > 0)
Keep matching elements
.filter_map(|s| s.parse().ok())
Filter + map in one pass
.sum::<i32>(); .count(); .max()
Common consumers
.fold(0, |acc, x| acc + x)
General reduction
.enumerate()
Pairs of (index, item)
.zip(other.iter())
Walk two iterators together
.take(5); .skip(2); .rev()
Slice and reverse lazily
.flat_map(|l| l.split(' '))
Map then flatten
.any(|x| x < 0); .all(|x| x > 0)
Short-circuit predicates
.find(|u| u.id == id); .position(...)
First match / its index
iter() &T; iter_mut() &mut T; into_iter() T
The three iteration modes
let add = move |x| x + base;
move closure takes ownership
.collect::<HashMap<_, _>>()
Collect pairs into a map

Error handling

11
fn run() -> Result<(), Box<dyn Error>>
Quick catch-all error type
fn main() -> anyhow::Result<()>
anyhow for applications
file.read().context("reading config")?;
anyhow: attach context
anyhow::bail!("invalid input: {x}");
Early return with an error
#[derive(thiserror::Error, Debug)]
thiserror for libraries
#[error("user {0} not found")] NotFound(u64),
Display message per variant
#[error(transparent)] Io(#[from] std::io::Error),
Auto-From wrapped errors
enum AppError { Db(String), Timeout }
Custom error enum
let n = do_it()?; // Err auto-converts
? uses From between error types
opt.expect("config must be loaded")
unwrap/expect: tests only
eprintln!("error: {e:#}");
Print the full error chain

Smart pointers & interior mutability

11
let b = Box::new(BigStruct::new());
Heap allocation, sole owner
enum List { Node(i32, Box<List>), Nil }
Box enables recursive types
let a = Rc::new(data); let b = Rc::clone(&a);
Shared owner, single thread
let a = Arc::new(data);
Shared owner across threads
let c = RefCell::new(0); *c.borrow_mut() += 1;
Runtime-checked mutation
Rc<RefCell<T>>
Shared + mutable (one thread)
let m = Mutex::new(0); *m.lock().unwrap() += 1;
Thread-safe mutation
Arc<Mutex<T>>
Shared + mutable across threads
let l = RwLock::new(map); l.read(); l.write();
Many readers or one writer
Cell::new(5).set(6);
Copy-type interior mutability
let w = Rc::downgrade(&a); w.upgrade()
Weak breaks reference cycles

Concurrency & async

13
let h = thread::spawn(|| work()); h.join()
Spawn and join a thread
thread::spawn(move || use(data))
move data into the thread
thread::scope(|s| { s.spawn(|| ...); })
Borrow locals in threads
let (tx, rx) = mpsc::channel();
Multi-producer channel
tx.send(job)?; let job = rx.recv()?;
Send / blocking receive
let n = Arc::new(Mutex::new(0));
Shared counter pattern
#[tokio::main] async fn main() { ... }
Async runtime entry point
async fn fetch() -> Result<Data>
Async function
let data = fetch().await?;
Await a future
let h = tokio::spawn(fetch()); h.await??;
Spawn an async task
let (a, b) = tokio::join!(f1(), f2());
Run futures concurrently
tokio::time::sleep(Duration::from_secs(1)).await;
Non-blocking sleep
tokio::select! { r = f1() => ..., _ = f2() => ... }
First future to finish wins

Cargo CLI

12
cargo new my-app
Create a binary project
cargo add serde --features derive
Add a dependency
cargo run
Build and run (debug)
cargo build --release
Optimized build
cargo check
Type-check fast, no binary
cargo test
Run tests (+ doc tests)
cargo clippy -- -D warnings
Lints, warnings as errors
cargo fmt
Format the whole project
cargo doc --open
Build and browse the docs
cargo update
Refresh Cargo.lock versions
cargo install ripgrep
Install a binary crate
cargo tree
Show the dependency graph

کوئی اندراج “:q” سے میل نہیں کھاتا۔


Rust چیٹ شیٹ کے بارے میں

یہ Rust چیٹ شیٹ زبان کو تصورات کے لحاظ سے ایک قابل تلاش صفحے پر ترتیب دیتی ہے: بنیادی باتیں، اونرشپ، بارونگ اور لائف ٹائمز، سٹرکٹس، اینمز اور impl بلاکس، پیٹرن میچنگ، Option اور Result، ٹریٹس اور جنرکس، کلیکشنز، اٹریٹرز اور کلوژرز، خرابیوں کی ہینڈلنگ، سمارٹ پوائنٹرز اور انٹیریئر میوٹیبلٹی، کنکرنسی اور async، اور Cargo کمانڈ لائن۔

اونرشپ Rust کا وہ حصہ ہے جسے لوگ بار بار دیکھنے آتے ہیں، اس لیے اسے لائف ٹائمز، بارونگ کے قواعد، Box، Rc، Arc اور RefCell کے ساتھ اپنا الگ حصہ ملتا ہے: روزمرہ سنٹیکس جیسے match arms، ? آپریٹر، اٹریٹر اڈاپٹرز اور ٹریٹس derive کرنے کے ساتھ ساتھ۔

اس گروپ کی ہر چیٹ شیٹ کی طرح یہ مفت اور کلائنٹ سائیڈ ہے: سرچ باکس سے قطاروں کو لائیو فلٹر کریں، چپکے رہنے والی فہرست مضامین سے حصوں کے درمیان کودیں، ایک کلک سے کوئی بھی اسنیپٹ کاپی کریں اور میز کے حوالے کے طور پر صفحہ پرنٹ کریں۔

Rust چیٹ شیٹ استعمال کرنے کا طریقہ

  1. شیٹ کھولیں اور حصوں کا جائزہ لیں، Basics اور Ownership & borrowing سے لے کر Cargo CLI تک۔
  2. lifetime، match یا Arc جیسا کوئی کلیدی لفظ تلاش کریں تاکہ شیٹ لائیو فلٹر ہو جائے۔
  3. جب آپ کو ناکام ہونے کا بامحاورہ طریقہ چاہیے ہو تو Option & Result یا Error handling پر جائیں۔
  4. Rust کوڈ کو اپنی کلپ بورڈ پر کاپی کرنے کے لیے کسی اسنیپٹ یا اس کے کاپی آئیکن پر کلک کریں۔
  5. مکمل Rust حوالے کی کاغذی کاپی کے لیے Print استعمال کریں۔

اکثر پوچھے جانے والے سوالات

بارہ حصے: بنیادی باتیں، اونرشپ، بارونگ اور لائف ٹائمز، سٹرکٹس، اینمز اور impl، پیٹرن میچنگ، Option اور Result، ٹریٹس اور جنرکس، کلیکشنز، اٹریٹرز اور کلوژرز، خرابیوں کی ہینڈلنگ، سمارٹ پوائنٹرز اور انٹیریئر میوٹیبلٹی، کنکرنسی اور async، اور Cargo CLI۔

جی ہاں۔ ایک مخصوص حصہ موو، بارو، میوٹیبل بارو، بارو چیکر کے قواعد اور لائف ٹائم اینوٹیشنز کو ہر قطار پر مختصر وضاحت کے ساتھ دکھاتا ہے۔

جی ہاں: Option اور Result کمبینیٹرز، ? آپریٹر، حسب ضرورت خرابی کی ٹائپس، From تبدیلیاں اور عام crate پیٹرنز ہر ایک کاپی کے لیے تیار اسنیپٹس کی صورت میں موجود ہیں۔

جی ہاں۔ کسی بھی قطار کے کوڈ یا اس کے کاپی آئیکن پر کلک کریں اور وہ فوراً کاپی ہو جاتا ہے۔

جی ہاں، یہ مکمل طور پر مفت ہے اور بغیر لاگ ان کے آپ کے براؤزر میں چلتا ہے۔

شیئر کریں

مقبول تلاشیں
rust چیٹ شیٹ rust سنٹیکس حوالہ rust اونرشپ اور بارونگ rust لائف ٹائمز کی وضاحت rust میں option اور result rust ٹریٹس اور جنرکس cargo کمانڈز
مدد چاہیے؟
اس ٹول میں کوئی مسئلہ ملا؟ ہماری ٹیم کو بتائیں۔
مسئلہ رپورٹ کریں

اس مفت ٹول کو اپنی ویب سائٹ پر شامل کریں: نیچے دیا گیا کوڈ کاپی اور پیسٹ کریں۔