Basics
1. Hello World
fn main() {
println!("Hello, world!");
}
2. Variables and Mutability
// Immutable variable
let x = 5;
// Mutable variable
let mut y = 10;
y = 15; // OK
// Constants
const MAX_POINTS: u32 = 100_000;
3. Data Types
// Scalar Types
let num: i32 = -10;
let floating: f64 = 3.14;
let is_true: bool = true;
let character: char = 'a';
// Compound Types
let tuple: (i32, f64, bool) = (500, 6.4, true);
let array: [i32; 5] = [1, 2, 3, 4, 5];
Control Flow
1. If Statement
let number = 6;
if number % 2 == 0 {
println!("Even");
} else {
println!("Odd");
}
2. Loop
let mut counter = 0;
loop {
counter += 1;
if counter == 5 {
break;
}
}
3. While Loop
let mut countdown = 5;
while countdown > 0 {
println!("{}", countdown);
countdown -= 1;
}
4. For Loop
let numbers = [1, 2, 3, 4, 5];
for num in numbers.iter() {
println!("{}", num);
}
Functions
1. Basic Function
fn greet(name: &str) {
println!("Hello, {}!", name);
}
greet("Ali");
2. Functions with Return Values
fn add(a: i32, b: i32) -> i32 {
a + b
}
let result = add(5, 3);
Error Handling
1. Result Type
fn divide(a: f64, b: f64) -> Result<f64, &'static str> {
if b == 0.0 {
return Err("Division by zero");
}
Ok(a / b)
}
match divide(10.0, 2.0) {
Ok(result) => println!("Result: {}", result),
Err(err) => println!("Error: {}", err),
}
Ownership, Borrowing, and Lifetimes
1. Ownership
let s1 = String::from("hello");
let s2 = s1; // Ownership moved to s2
2. Borrowing
fn calculate_length(s: &String) -> usize {
s.len()
}
let s = String::from("hello");
let len = calculate_length(&s); // Borrowed s
3. Lifetimes
fn longest<'a>(s1: &'a str, s2: &'a str) -> &'a str {
if s1.len() > s2.len() {
s1
} else {
s2
}
}
Advanced Concepts
1. Structs
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
}
let rect = Rectangle { width: 10, height: 20 };
let area = rect.area();
2. Enums
enum Coin {
Penny,
Nickel,
Dime,
Quarter,
}
fn value_in_cents(coin: Coin) -> u8 {
match coin {
Coin::Penny => 1,
Coin::Nickel => 5,
Coin::Dime => 10,
Coin::Quarter => 25,
}
}
3. Traits
trait Vehicle {
fn drive(&self);
}
struct Car;
impl Vehicle for Car {
fn drive(&self) {
println!("Car is driving...");
}
}
let car = Car;
car.drive();
Conclusion
This Rust cheatsheet provides a quick overview of essential concepts and syntax in Rust programming language, catering to beginners and intermediate developers alike. Whether you're building a small utility or a complex system, Rust's safety features and performance make it an excellent choice for various applications.
Top comments (0)