Idiomatic Rust लिखना
In this page:
Prefer Iterators Over Manual Loops
Idiomatic Rust अक्सर transformations को .map() और .filter() जैसे iterator adapters से express करता है बजाय mutable accumulator variables वाले manually लिखे loops के, क्योंकि यह ज़्यादा declarative और कम error-prone है।
उदाहरण: Prefer Iterators Over Manual Loops
// Entry point: execution of the program starts here
fn main() {
// Declare an immutable variable `numbers`, set to `vec![1, 2, 3, 4, 5]`
let numbers = vec![1, 2, 3, 4, 5];
// Declare an immutable variable `sum_of_squares` (an integer), set to `numbers.iter().map(|n| n * n).sum()`
let sum_of_squares: i32 = numbers.iter().map(|n| n * n).sum();
// Print "{}" to the console, substituting in `sum_of_squares` (with a trailing newline)
println!("{}", sum_of_squares);
}
Login to try C/C++/Java/PHP code in the editor
Borrow Instead of Clone When Possible
एक borrow-checker complaint से बचने के लिए .clone() तक पहुंचना आमतौर पर एक संकेत है कि code को इसके बजाय borrow करने के लिए restructure किया जा सकता था, अनावश्यक memory allocation और copying से बचते हुए।
उदाहरण: Borrow Instead of Clone When Possible
// Define the function `print_length` taking `s`
fn print_length(s: &str) {
// Print "Length: {}" to the console, substituting in `s.len()` (with a trailing newline)
println!("Length: {}", s.len());
}
// Entry point: execution of the program starts here
fn main() {
// Declare an immutable variable `text`, set to `String::from("idiomatic")`
let text = String::from("idiomatic");
print_length(&text);
// Print "Still usable: {}" to the console, substituting in `text` (with a trailing newline)
println!("Still usable: {}", text);
}
Login to try C/C++/Java/PHP code in the editor
Use the Type System to Prevent Bugs
Idiomatic Rust Option, Result, और enums पर निर्भर करता है invalid states को represent करना असंभव बनाने के लिए, bugs की पूरी categories को runtime checks के बजाय compile time पर पकड़ते हुए।
उदाहरण: Use the Type System to Prevent Bugs
// Define an enum `PaymentStatus` listing its possible variants
enum PaymentStatus {
Pending,
Completed(f64),
Failed(String),
}
// Define the function `describe` taking `status` and returning a String
fn describe(status: PaymentStatus) -> String {
// Match on `status` and branch by pattern
match status {
PaymentStatus::Pending => String::from("still pending"),
PaymentStatus::Completed(amount) => format!("completed for ${}", amount),
PaymentStatus::Failed(reason) => format!("failed: {}", reason),
}
}
// Entry point: execution of the program starts here
fn main() {
// Print "{}" to the console, substituting in `describe(PaymentStatus::Completed(49.99))` (with a trailing newline)
println!("{}", describe(PaymentStatus::Completed(49.99)));
}
Login to try C/C++/Java/PHP code in the editor
Listen to the Compiler
Rust compiler की warnings, जैसे एक unused mut या एक unused variable, आमतौर पर एक genuine simplification opportunity की ओर point कर रही होती हैं, और idiomatic code उन्हें suppress करने के बजाय seriously लेता है।
उदाहरण: Listen to the Compiler
fn main() {
let value = 100; // no mut needed since it is never reassigned
println!("Clean, warning-free code: {}", value);
}
Login to try C/C++/Java/PHP code in the editor
- Borrow checker से निपटने से बचने के लिए हर जगह
.clone()overuse करना, code को सही से borrow करने के लिए restructure करने के बजाय। - उन tasks के लिए verbose manual loops लिखना जिन्हें idiomatic Rust
.map()/.filter()जैसे iterator adapters से express करता। - Compiler warnings (जैसे unused
mutया dead code) को नज़रअंदाज़ करना बजाय उन्हें cleaner code की ओर helpful hints मानने के।
- Idiomatic Rust manual loops की तुलना में iterator adapters पसंद करता है जब वे वही logic ज़्यादा clearly express करते हैं।
- Cloning की तुलना में borrowing पसंद करना अनावश्यक allocations से बचाता है और code को Rust की ownership philosophy के करीब रखता है।
- Type system (जैसे
Option/Result) का लाभ उठाकर invalid states को unrepresentable बनाना अच्छे Rust code की एक पहचान है। - Compiler warnings पर ध्यान देना अक्सर code को simplify या correct करने के मौके उजागर करता है।
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: