DEV Community

Oludayo Adeoye
Oludayo Adeoye

Posted on

🦀 Rust Master Class - Chapter 2: Basic Programming

🦀 Rust Master Class - Chapter 2: Basic Programming


My code wouldn't compile. Again. I'd been fighting the borrow checker for three hours, and I was about to give up. Then I realized: the compiler wasn't my enemy. It was the strict teacher I never knew I needed.


In Rust, variables, data types, and functions form the core of every program . Understanding these basics is essential for managing how data is stored and processed.

1. Variables and Mutability

In Rust, variables are immutable by default, meaning once you bind a value to a name, you cannot change it [2-4]. To make a variable changeable, you must use the mut keyword [3-5].

  • Shadowing: You can declare a new variable with the same name as a previous one, which "shadows" the first variable [6-9]. This allows you to change the type of a value while keeping the same name [7-9].
  • Constants: Unlike variables, constants are always immutable and are declared using the const keyword. They must have a specified type and are typically used for values that will never change [2-4, 6].

Code Example:

fn main() {
    let value = 5;          // Immutable variable 
    // Create a mutable variable
    let mut borrowed = 10;     // Mutable variable 
    borrowed = 15;             // Works because borrowed is mutable

    // Create a new variable
    let s = 100;         // Shadowing 
    // Create a new variable
    let s = "A";        // s is now a string instead of an integer 
}
Enter fullscreen mode Exit fullscreen mode

2. Data Types

Rust is a statically typed language, meaning it must know the types of all variables at compile time . Data types are divided into Scalar and Compound categories [6-9].

Scalar Types

These represent a single value [6-9]:

  • Integers: Whole numbers like i32 (signed) or u32 (unsigned) [11-14].
  • Floating-point: Numbers with decimal points, such as f32 and f64 [7-9, 11].
  • Booleans: Either true or false .
  • Characters: Single Unicode values specified with single quotes, like 'a' [11, 15-17].

Compound Types

These group multiple values into one type [6-9]:

  • Tuples: Fixed-length groups of multiple types. Elements are accessed via dot notation (e.g., tuple.0) [18-20].
  • Arrays: Fixed-length groups of the same type [12-14].
  • Vectors: Growable lists of the same type, created with the vec! macro [21-23].
  • Strings: Rust has two main string types: string literals (&str) which are fixed, and String, which is growable and stored on the heap [7, 24-27].

Code Example:

    // Create a new variable
let my_tuple: (&str, i100) = ("Salary", 100_000); // Tuple 
    // Create a new variable
let my_array: [i100; 3] = ;             // Array 
    // Create a mutable variable
let mut my_vec = vec!;                  // Vector 
my_vec.push(4);                                 // Adding to vector 
Enter fullscreen mode Exit fullscreen mode

3. Functions

Functions are the building blocks of Rust code and are defined using the fn keyword [31-33].

  • Parameters: You must declare the type of each parameter in the function signature [31-33].
  • Return Values: To return a value, use the -> symbol followed by the return type [31-33].
  • Expressions vs. Statements: In Rust, if the last line of a function is an expression (meaning it has no semicolon), that value is automatically returned [31-33].

Code Example:

// Basic function with no input or output 
fn hello() {
    // Output to console
    println!("Hello!");
}

// Function with inputs and a return value 
fn multiplication(a: i100, b: i100) -> i100 {
    a * b // Expression: returns the output 
}

fn main() {
    hello();
    // Create a new variable
    let output = multiplication(10, 5);
    // Output to console
    println!("Result: {}", output);
}
Enter fullscreen mode Exit fullscreen mode

By combining these concepts, you can structure your programs effectively while taking advantage of Rust's compile-time type checking to ensure safety .


📖 Download the full PDF: https://drive.google.com/file/d/125TgZUOklMfZViG4Di7N3ulvdx3cSqfs/view?usp=sharing

Part 2 of the Rust Master Class series — STEM EdTech | Automation Consulting | Rust Tutoring

RustLang #Programming #LearnToCode #STEM #EdTech


📚 Practice Resources

GitHub Repository: https://github.com/PacktPublishing/Rust-Programming-Master-Class-from-Beginner-to-Expert

Try it yourself: https://play.rust-lang.org/

Run the code from this chapter in the Rust playground, then clone the repo to continue your Rust journey!


Part 2 of the Rust Master Class series — STEM EdTech | Automation Consulting | Rust Tutoring

RustLang #Programming #LearnToCode #STEM #EdTech

Top comments (0)