Obsidian/3-99 Research/Rust/Chapter 3 - Common Programming Concepts.md

1.6 KiB

#Rust

The quick brown fox jumps over the lazy dog. The dog stays blissfully asleep. :)

What is Chapter 3?

Chapter three is about common programming concepts that I would be familiar with from other languages. This chapter covers variables, mutability, data types, functions, comments, and control flow.

3.1 Variables and Mutability

Variables

Rust defines variables kind of like C does:

let x = 7; // x is 7!

but Rust also allows explicit declaration of types when defining a variable:

let x: u32 = 7; // x is a 32 bit unsigned integer with value 7
let y: f32 = 7.0; // y is a 32 bit float with value of 7.0

Variables can be defined in specific scopes that do not escape the inner scope:

let x: u32 = 4;
{
    let mut x = x;
    x += 2;
}

println!("{x}")
>> 4 // NOT 6.

Mutability

All variables in Rust are immutable unless specifically mentioned. This is part of ensuring memory safety--you will not be able to overwrite variables unless you declare that they can change over time. Here's an example:

let x: u32 = 2;
x += 2; // Will fail. x is not mutable

let mut y: u32 = 2;
y += 2; // Will work, since y is mutable

Constants

Constants are a special case in Rust. They are immutable variables just like let, but they have a special ability to be defined in the global scope, where let may not be. Here's an example.

const TWO_PLUS_THREE: u32 = 2 + 3;
fn main() {
    println!("{TWO_PLUS_THREE}");
}
>> 5

Constants are by convention written in UPPER_CAMEL_CASE.

3.2 Data Types

3.3 Functions

3.4 Comments

3.5 Control Flow