Rust Programming Language: A Complete Beginner's Guide
Rust Programming Language: A Complete Beginner's Guide
Welcome to Rust! This guide will teach you everything you need to know to get started with Rust programming, even if you've never coded before.
What is Rust?
Rust is a modern programming language that's fast, reliable, and memory-safe. It was created by Mozilla and first released in 2010. Rust is used for building everything from web applications to operating systems, and it's gaining popularity in the tech industry.
Why Learn Rust?
- Memory Safety: Rust prevents common programming errors like buffer overflows and null pointer dereferences
- Speed: Rust compiles to fast machine code, similar to C and C++
- Concurrency: Built-in support for safe parallel programming
- Growing Community: Increasingly popular in web development, systems programming, and more
Setting Up Your Environment
Before we start coding, you need to install Rust:
Install Rust:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | shVerify Installation:
rustc --versionCreate Your First Project:
cargo new hello_rust cd hello_rust
Basic Rust Concepts
1. Hello, World!
Let's start with the classic "Hello, World!" program:
fn main() {
println!("Hello, world!");
}
Key Points:
fndeclares a functionmain()is the entry point of every Rust programprintln!prints text to the console (note the exclamation mark!)- Semicolons end statements
2. Variables and Data Types
Variables in Rust
In Rust, variables are immutable by default:
fn main() {
let x = 5; // x is immutable
println!("The value of x is: {}", x);
// This would cause an error:
// x = 10; // Error! Cannot assign to immutable variable
// To make a variable mutable, use `mut`:
let mut y = 5;
println!("The value of y is: {}", y);
y = 10; // This works!
println!("The new value of y is: {}", y);
}
Common Data Types
fn main() {
// Numbers
let integer = 42; // i32 (32-bit signed integer)
let float = 3.14; // f64 (64-bit floating point)
// Boolean
let is_true = true;
let is_false = false;
// Character (single character)
let letter = 'R';
// String (text)
let greeting = "Hello, Rust!";
println!("Integer: {}, Float: {}, Boolean: {}, Letter: {}, String: {}",
integer, float, is_true, letter, greeting);
}
3. Functions
Functions in Rust follow a specific pattern:
fn main() {
greet("Alice");
let result = add(5, 3);
println!("5 + 3 = {}", result);
}
// Function without return value
fn greet(name: &str) {
println!("Hello, {}!", name);
}
// Function with return value
fn add(a: i32, b: i32) -> i32 {
return a + b; // or simply: a + b
}
4. Control Flow
If Expressions
fn main() {
let number = 10;
if number < 5 {
println!("Number is less than 5");
} else if number > 15 {
println!("Number is greater than 15");
} else {
println!("Number is between 5 and 15");
}
// If as an expression
let condition = true;
let number = if condition { 5 } else { 6 };
println!("The value is: {}", number);
}
Loops
fn main() {
// While loop
let mut counter = 0;
while counter < 3 {
println!("Counter: {}", counter);
counter += 1;
}
// For loop
for i in 0..3 { // 0, 1, 2 (not including 3)
println!("For loop iteration: {}", i);
}
// Loop through array
let fruits = ["apple", "banana", "cherry"];
for fruit in fruits.iter() {
println!("Fruit: {}", fruit);
}
}
5. Collections
Arrays
fn main() {
// Array with explicit type
let numbers: [i32; 4] = [1, 2, 3, 4];
// Array without explicit type (inferred)
let colors = ["red", "green", "blue"];
println!("First color: {}", colors[0]);
println!("Array length: {}", numbers.len());
}
Vectors (Dynamic Arrays)
fn main() {
// Create a vector
let mut fruits = Vec::new();
// Add items
fruits.push("apple");
fruits.push("banana");
// Or create with initial values
let mut numbers = vec![1, 2, 3, 4];
println!("First fruit: {}", fruits[0]);
println!("Vector length: {}", numbers.len());
}
6. Ownership and References
This is one of Rust's most important concepts:
fn main() {
// Ownership example
let s1 = String::from("Hello");
let s2 = s1; // s1 is moved to s2, s1 can no longer be used
// println!("{}", s1); // This would cause an error!
println!("{}", s2);
// Using references to avoid moving
let s3 = String::from("Hello");
let s4 = &s3; // s4 is a reference to s3
println!("s3: {}, s4: {}", s3, s4); // Both work fine!
}
Key Rust Concepts for Beginners
1. The let Keyword
- Always use
letto declare variables - Use
mutfor mutable variables:let mut x = 5; - Rust infers types when possible, but you can be explicit:
let x: i32 = 5;
2. Semicolons
- End statements with semicolons (
;) - Expressions don't need semicolons
3. Functions
- Use
fnkeyword to define functions - Parameters are declared like
param_name: type - Return types are specified with
-> type
4. String vs &str
Stringis a mutable, owned string&stris an immutable string slice (reference to string data)
Practice Exercises
Try these simple exercises to practice what you've learned:
- Create a program that asks for your name and says hello
- Write a function that takes two numbers and returns their sum
- Create a loop that prints numbers 1 to 10
- Make an array of your favorite colors and print them
Next Steps
Once you're comfortable with these basics, consider learning:
- Structs (custom data types)
- Enums (enumerations)
- Traits (interfaces)
- Error handling
- Testing in Rust
- Cargo (Rust's package manager and build system)
Useful Resources
- The Rust Programming Language Book
- Rust by Example
- Rust Playground - Online Rust compiler
- Rust Documentation
Common Mistakes for Beginners
- Forgetting semicolons - They're required at the end of statements
- Trying to use moved values - Remember ownership rules
- Confusing
Stringand&str- Know when to use each one - Not using
mutfor mutable variables - Rust won't let you change immutable ones
Summary
Rust is a powerful language that prioritizes safety without sacrificing performance. While it has a learning curve, especially around ownership concepts, it's an excellent choice for both beginners and experienced developers who want to write reliable, fast code.
Start with the basics we've covered here, practice regularly, and don't be afraid to experiment in the Rust Playground. Happy coding!