Introduction to Rust
Rust is a systems programming language focused on safety, speed, and concurrency. It is designed to prevent common programming errors such as null pointer dereferencing and data races. Rust is widely used for building reliable and efficient software.
Why Rust?
Rust is a great choice for systems programming because:
- Memory Safety: Rust ensures memory safety without a garbage collector.
- Concurrency: Rust provides powerful tools for concurrent programming.
- Performance: Rust offers performance comparable to C and C++.
- Modern Syntax: Rust has a clean and expressive syntax.
- Community and Ecosystem: Rust has a growing community and a rich ecosystem of libraries.
Installation Guide
To install Rust, follow these steps:
- Visit the official Rust website: rust-lang.org.
- Download and run the installer for your operating system.
- Follow the on-screen instructions to complete the installation.
- Verify the installation by running
rustc --version
in your terminal.
Cargo Overview
Cargo is Rust's package manager and build system. It helps you manage dependencies, compile your code, and run tests. Here are some common Cargo commands:
# Create a new Rust project
cargo new my_project
# Build the project
cargo build
# Run the project
cargo run
# Run tests
cargo test
Basic Syntax
Rust has a clean and expressive syntax. Here are some examples:
// Variables and Mutability
let x = 5; // Immutable variable
let mut y = 10; // Mutable variable
y = 15;
// Functions
fn add(a: i32, b: i32) -> i32 {
a + b
}
// Control Flow
let number = 7;
if number < 5 {
println!("Condition was true");
} else {
println!("Condition was false");
}
// Loops
for i in 0..5 {
println!("Value: {}", i);
}
Interactive Code Examples
Try running these examples in your Rust environment to see how they work!
// Interactive Example
fn main() {
let name = "Rust";
println!("Hello, {}!", name);
}
Practice Problems
Test your understanding with these practice problems:
- Write a Rust program to print the first 10 natural numbers.
- Write a Rust function to calculate the factorial of a number.
- Write a Rust program to check if a number is prime.