Rust Basics Syntax
Variables:
variables are immutable by their default definition that means they heritage of being invariable after the values assigned.
The mutable variable is created by using the "mut" keyword.
Example:
fn main() {
let x = 5; // immutable variable
println!("x = {}", x);
let mut y = 10; // mutable variable
y = 15;
println!("y = {}", y);
}
Data Types:
Rust is a statically typed language in which the type of every variable is defined, and it happens before the execution time(compile time).
Some basic data types include:
- Integers: i8, i16, i32, i64, i128 (signed), and u8, u16, u32, u64, u128 (unsigned).
- Floating-point numbers: f32 and f64
- Booleans: bool
- Characters: char.
- Tuples: A way to group multiple values of different types.
- Arrays: A fixed-size collection of elements of the same type.
Example:
fn main() {
let a: i32 = 10;
let b: f64 = 20.5;
let c: bool = true;
let d: char = 'A';
let tuple: (i32, f64, char) = (10, 20.5, 'A');
let array: [i32; 3] = [1, 2, 3];
println!("a = {}", a);
println!("b = {}", b);
println!("c = {}", c);
println!("d = {}", d);
println!("tuple = {:?}", tuple);
println!("array = {:?}", array);
}
Constants and Mutability
Constants:
The constants will be always immutable, and must be declared with a const keyword. They should have their type and that's usually when they're used for values that won't change.
Example:
const MAX_POINTS: u32 = 100_000;
fn main() {
println!("The maximum points are: {}", MAX_POINTS);
}
Mutability:
In Rust, you use the mut keyword to make a variable mutable, allowing its value to change.
fn main() {
let mut counter = 0;
counter += 1;
println!("Counter: {}", counter);
}
Control Structures (if-else, loops)
if-else:
Rust has the if statement which allows running block of code only if the condition is actually true.
You can also use else and else if for additional conditions.
Example:
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 3 or 4");
}
}
Loops:
Rust provides several ways to loop through code: loop, while, and for.
- loop: It loops through a piece of code forever until the point where you intentionally leave it.
- while: Able to loop through a block of code as long as the condition is correct.
- for: Doubles the value for every item in the sequence.
Example:
// loop
fn main() {
let mut count = 0;
loop {
count += 1;
if count == 3 {
break;
}
println!("Count: {}", count);
}
}
// 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);
}
for number in (1..4).rev() {
println!("{}!", number);
}
println!("LIFTOFF!!!");
}
These Rust language basics give you a foundation for writing and working with programs that execute Rust code.