Rust Programming Quick Guide
Page 1: Introduction and Basics
What is Rust?
Rust is a modern, systems programming language designed for safety,
performance, and concurrency. It eliminates common programming errors
such as null pointer dereferencing and data races while providing powerful
tools for building efficient applications.
Key Features
1. Memory Safety: Ownership system ensures no data races or dangling
pointers.
2. Performance: Comparable to C and C++, with zero-cost abstractions.
3. Concurrency: Fearless concurrency without compromising safety.
4. Tooling: Built-in package manager (Cargo), testing, and
documentation tools.
Setting Up
1. Install Rust:
o Download from https://www.rust-lang.org.
o Run the following command to install:
bash
Copy code
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
2. Verify Installation:
bash
Copy code
rustc --version
3. Install Visual Studio Code (Optional):
o Add the Rust extension for better development experience.
Hello, World!
1. Create a new project:
bash
Copy code
cargo new hello_world
cd hello_world
2. Edit the main file:
rust
Copy code
fn main() {
println!("Hello, World!");
3. Run the program:
bash
Copy code
cargo run
Basic Syntax
1. Variables:
o Immutable by default:
rust
Copy code
let x = 10;
o Mutable variables:
rust
Copy code
let mut y = 20;
y = 25;
2. Data Types:
o Integer: i32, u64
o Float: f32, f64
o Boolean: bool
o Character: char
o Tuple and Array
3. Control Flow:
o If-else:
rust
Copy code
if x > 5 {
println!("x is greater than 5");
} else {
println!("x is 5 or less");
o Loops:
rust
Copy code
for i in 1..5 {
println!("{}", i);
Key Concepts
1. Ownership:
o Each value in Rust has a single owner.
o Ownership rules:
Only one owner at a time.
When the owner goes out of scope, the value is dropped.
2. References and Borrowing:
o Borrowing allows multiple references without transferring
ownership:
rust
Copy code
let s = String::from("hello");
let len = calculate_length(&s);
fn calculate_length(s: &String) -> usize {
s.len()
Page 2: Advanced Topics and Examples
Common Data Structures
1. Vector:
rust
Copy code
let mut v = vec![1, 2, 3];
v.push(4);
for i in &v {
println!("{}", i);
}
2. HashMap:
rust
Copy code
use std::collections::HashMap;
let mut scores = HashMap::new();
scores.insert("Alice", 10);
scores.insert("Bob", 20);
Functions
1. Defining Functions:
rust
Copy code
fn add(a: i32, b: i32) -> i32 {
a+b
2. Closures:
rust
Copy code
let sum = |a, b| a + b;
println!("{}", sum(5, 3));
Error Handling
1. Result and Option:
o Handling errors with Result:
rust
Copy code
fn divide(a: i32, b: i32) -> Result<i32, String> {
if b == 0 {
Err(String::from("Cannot divide by zero"))
} else {
Ok(a / b)
o Handling nullable values with Option:
rust
Copy code
let maybe_value: Option<i32> = Some(42);
if let Some(val) = maybe_value {
println!("{}", val);
Concurrency
1. Threads:
rust
Copy code
use std::thread;
let handle = thread::spawn(|| {
for i in 1..10 {
println!("Thread: {}", i);
});
handle.join().unwrap();
2. Channels:
rust
Copy code
use std::sync::mpsc;
use std::thread;
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
tx.send("Hello from thread").unwrap();
});
println!("{}", rx.recv().unwrap());
Traits
1. Defining Traits:
rust
Copy code
trait Greet {
fn greet(&self);
struct Person;
impl Greet for Person {
fn greet(&self) {
println!("Hello!");
}
}
Macros
1. Common Macros:
o println!: Prints to the console.
o vec!: Creates a vector.
rust
Copy code
let numbers = vec![1, 2, 3];
Useful Commands
1. Build a Project:
bash
Copy code
cargo build
2. Run Tests:
bash
Copy code
cargo test
3. Generate Documentation:
bash
Copy code
cargo doc --open
Learning Resources
Official Documentation: https://doc.rust-lang.org
The Rust Book: https://doc.rust-lang.org/book/
Rust Playground: https://play.rust-lang.org