Introduction to Programming in Rust
Rust is a modern systems programming language designed for performance, safety, and concurrency. It guarantees memory safety without a garbage collector, making it ideal for building reliable and efficient software. Rust's unique features, such as ownership and borrowing, prevent common programming errors like null pointer dereferencing and data races.
This guide will introduce you to the fundamentals of Rust programming, helping you write safe and performant code for a variety of applications.
Table of Contents
- What is Rust?
- Setting Up Your Environment
- Variables and Data Types
- Control Flow
- Functions
- Ownership and Borrowing
- Structs and Enums
- Collections
- Error Handling
- Concurrency
What is Rust?
Rust is a systems programming language that focuses on safety, speed, and concurrency. It is widely used in areas like web assembly, game development, and operating systems.
1// Example: Your first Rust program
2fn main() {
3 println!("Hello, Rust Programming!");
4}
Setting Up Your Environment
To write and run Rust programs, you need to install the Rust toolchain using rustup
. Follow the instructions on the official Rust website.
1# Example: Compiling and running a Rust program
2rustc main.rs
3./main
Variables and Data Types
Rust is statically typed, meaning variable types are determined at compile time. Common data types include integers, floats, booleans, and characters.
1// Example: Declaring variables
2fn main() {
3 let age: i32 = 25;
4 let height: f64 = 5.9;
5 let name: &str = "Alice";
6 let is_student: bool = true;
7
8 println!("Name: {}, Age: {}, Height: {}", name, age, height);
9}
Control Flow
Rust supports if
, else
, match
, and loops (loop
, while
, for
) for controlling program flow.
1// Example: Conditional statement
2fn main() {
3 let age = 18;
4
5 if age >= 18 {
6 println!("You are an adult.");
7 } else {
8 println!("You are a minor.");
9 }
10}
Functions
Functions are defined using the fn
keyword. Rust functions can return values using the return
keyword or implicitly by omitting the semicolon.
1// Example: Function
2fn add(a: i32, b: i32) -> i32 {
3 a + b
4}
5
6fn main() {
7 let result = add(5, 10);
8 println!("Result: {}", result); // 15
9}
Ownership and Borrowing
Rust's ownership system ensures memory safety by enforcing rules at compile time. Variables can be moved, borrowed, or cloned.
1// Example: Ownership
2fn main() {
3 let s1 = String::from("Hello");
4 let s2 = s1; // s1 is moved to s2
5 // println!("{}", s1); // This would cause a compile-time error
6 println!("{}", s2);
7}
Structs and Enums
Structs and enums are used to define custom data types in Rust.
1// Example: Struct
2struct Person {
3 name: String,
4 age: u8,
5}
6
7fn main() {
8 let person = Person {
9 name: String::from("Alice"),
10 age: 25,
11 };
12
13 println!("Name: {}, Age: {}", person.name, person.age);
14}
Collections
Rust provides collections like vectors, hash maps, and strings for storing and manipulating data.
1// Example: Vector
2fn main() {
3 let numbers = vec![1, 2, 3, 4, 5];
4
5 for number in numbers {
6 println!("Number: {}", number);
7 }
8}
Error Handling
Rust uses the Result
and Option
types for error handling, ensuring that errors are handled explicitly.
1// Example: Result type
2fn divide(a: f64, b: f64) -> Result<f64, String> {
3 if b == 0.0 {
4 Err(String::from("Division by zero"))
5 } else {
6 Ok(a / b)
7 }
8}
9
10fn main() {
11 match divide(10.0, 0.0) {
12 Ok(result) => println!("Result: {}", result),
13 Err(e) => println!("Error: {}", e),
14 }
15}
Concurrency
Rust provides powerful concurrency primitives like threads and channels for writing concurrent programs.
1// Example: Threads
2use std::thread;
3
4fn main() {
5 let handle = thread::spawn(|| {
6 println!("Hello from a thread!");
7 });
8
9 handle.join().unwrap();
10}