CodeToLive

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:

Installation Guide

To install Rust, follow these steps:

  1. Visit the official Rust website: rust-lang.org.
  2. Download and run the installer for your operating system.
  3. Follow the on-screen instructions to complete the installation.
  4. 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:

  1. Write a Rust program to print the first 10 natural numbers.
  2. Write a Rust function to calculate the factorial of a number.
  3. Write a Rust program to check if a number is prime.
Next: Variables and Data Types