In this section, we will cover the fundamental syntax and structure of a Rust program. Understanding these basics is crucial for writing and reading Rust code effectively.

Key Concepts

  1. Comments
  2. Variables and Constants
  3. Functions
  4. Control Flow
  5. Modules and Crates

  1. Comments

Comments are used to annotate the code and are ignored by the compiler. Rust supports two types of comments:

  • Line Comments: Start with // and continue to the end of the line.
  • Block Comments: Start with /* and end with */.
// This is a line comment

/*
This is a block comment.
It can span multiple lines.
*/

  1. Variables and Constants

Variables

Variables in Rust are immutable by default. To declare a mutable variable, use the mut keyword.

fn main() {
    let x = 5; // Immutable variable
    let mut y = 10; // Mutable variable
    y = 15; // This is allowed because y is mutable
    println!("x: {}, y: {}", x, y);
}

Constants

Constants are always immutable and must have their type specified. They are declared using the const keyword.

const MAX_POINTS: u32 = 100_000;

  1. Functions

Functions are declared using the fn keyword. The main function is the entry point of a Rust program.

fn main() {
    println!("Hello, world!");
}

fn add(a: i32, b: i32) -> i32 {
    a + b // No semicolon means this is an expression that returns a value
}

  1. Control Flow

If-Else

Rust's if statements are similar to those in other languages but do not require parentheses around the condition.

fn main() {
    let number = 6;

    if number % 4 == 0 {
        println!("The number is divisible by 4");
    } else if number % 3 == 0 {
        println!("The number is divisible by 3");
    } else {
        println!("The number is not divisible by 4 or 3");
    }
}

Loops

Rust provides several ways to perform loops: loop, while, and for.

Loop

fn main() {
    let mut counter = 0;

    loop {
        counter += 1;
        if counter == 10 {
            break;
        }
    }
    println!("Counter: {}", counter);
}

While

fn main() {
    let mut number = 3;

    while number != 0 {
        println!("{}!", number);
        number -= 1;
    }
    println!("LIFTOFF!!!");
}

For

fn main() {
    let a = [10, 20, 30, 40, 50];

    for element in a.iter() {
        println!("The value is: {}", element);
    }
}

  1. Modules and Crates

Modules

Modules are used to organize code into namespaces. They are declared using the mod keyword.

mod my_module {
    pub fn say_hello() {
        println!("Hello from my_module!");
    }
}

fn main() {
    my_module::say_hello();
}

Crates

Crates are the fundamental compilation units in Rust. A crate can be a binary or a library.

  • Binary Crate: Has a main function and can be executed.
  • Library Crate: Does not have a main function and is intended to be used as a dependency.

Practical Exercise

Exercise 1: Basic Syntax

Write a Rust program that:

  1. Declares a mutable variable and changes its value.
  2. Defines a function that takes two integers and returns their sum.
  3. Uses an if-else statement to check if a number is even or odd.
  4. Uses a for loop to iterate over an array and print its elements.

Solution

fn main() {
    // Step 1: Mutable variable
    let mut x = 5;
    println!("Initial value of x: {}", x);
    x = 10;
    println!("Updated value of x: {}", x);

    // Step 2: Function to add two numbers
    let sum = add(3, 4);
    println!("Sum of 3 and 4: {}", sum);

    // Step 3: If-else to check even or odd
    let number = 7;
    if number % 2 == 0 {
        println!("{} is even", number);
    } else {
        println!("{} is odd", number);
    }

    // Step 4: For loop to iterate over an array
    let array = [1, 2, 3, 4, 5];
    for element in array.iter() {
        println!("Array element: {}", element);
    }
}

fn add(a: i32, b: i32) -> i32 {
    a + b
}

Summary

In this section, we covered the basic syntax and structure of Rust programs, including comments, variables, constants, functions, control flow, and modules. These foundational elements are essential for writing and understanding Rust code. In the next module, we will delve deeper into basic concepts such as variables, data types, and functions.

Rust Programming Course

Module 1: Introduction to Rust

Module 2: Basic Concepts

Module 3: Ownership and Borrowing

Module 4: Structs and Enums

Module 5: Collections

Module 6: Error Handling

Module 7: Advanced Concepts

Module 8: Concurrency

Module 9: Advanced Features

Module 10: Project and Best Practices

© Copyright 2024. All rights reserved