Rust Syntax

Key Elements of Rust Syntax

1. Variables and Constants

Variables: Declare mutable and immutable variables using let.

  • Immutable (default):
let x = 10; // Immutable variable
println!("Value of x: {}", x);
  • Mutable:
let mut y = 20; // Mutable variable
y = 25;
println!("Updated value of y: {}", y);

Constants: Use const for values that do not change. Constants must have a type specified.

const MAX_LIMIT: u32 = 100;
println!("Maximum Limit: {}", MAX_LIMIT);

2. Data Types

Rust is a statically typed language, requiring every variable to have a defined data type.

Scalar Types:

  • Integer: i8, i16, i32, u8, etc. Floating-point: f32, f64. Boolean: bool. Character: char.
let a: i32 = 5; // Integer
let b: f64 = 3.14; // Float
let is_active: bool = true; // Boolean
let emoji: char = 'šŸ˜Š'; // Character
println!("a: {}, b: {}, is_active: {}, emoji: {}", a, b, is_active, emoji);

Compound Types:

  • Tuple:
let tup: (i32, f64, u8) = (500, 6.4, 1);
println!("Tuple values: {}, {}, {}", tup.0, tup.1, tup.2);
  • Array:
let arr = [1, 2, 3, 4];
println!("First element: {}", arr[0]);

3. Functions

Functions in Rust are defined using the fn keyword.

  • Basic function:
fn greet() {
println!("Hello, Rust!");
}
greet();
  • Function with parameters:
fn add(a: i32, b: i32) -> i32 {
a + b
}
println!("Sum: {}", add(5, 3));

4. Control Flow

Conditional Statements:

  • if and else:
let number = 10;
if number > 0 {
println!("Positive number");
} else {
println!("Non-positive number");
}

Loops:

  • loop:
let mut count = 0;
loop {
count += 1;
if count == 5 {
break;
}
println!("Count: {}", count);
}
  • while loop:
let mut num = 5;
while num > 0 {
println!("{}", num);
num -= 1;
}
  • for loop:
let numbers = [10, 20, 30];
for num in numbers.iter() {
println!("{}", num);
}

5. Ownership and Borrowing

Rustā€™s ownership system ensures memory safety.

  • Ownership:
let s = String::from("Hello");
println!("{}", s); // Ownership is transferred here.
  • Borrowing:
let s = String::from("Rust");
let len = calculate_length(&s); // Borrowing reference
println!("The length of '{}' is {}.", s, len);

fn calculate_length(s: &String) -> usize {
s.len()
}

6. Comments

Rust supports single-line and multi-line comments.

  • Single-line:
// This is a single-line comment
let x = 5;
  • Multi-line:
/* This is a 
multi-line comment */
let y = 10;

7. Macros

Macros like println! are used frequently in Rust. They end with ! and perform metaprogramming tasks.

println!("Rust version: {}", "1.72.0");

Example Program: Combining Syntax Elements

fn main() {
const PI: f64 = 3.14159;
let radius = 5.0;

let area = calculate_area(radius);
println!("The area of a circle with radius {} is {}", radius, area);
}

fn calculate_area(r: f64) -> f64 {
PI * r * r
}

Exercises

  1. Create a program to find the maximum of two numbers using an if-else statement.
  2. Write a program to iterate over an array and print its elements.
  3. Implement a function to calculate the factorial of a number using recursion.

Leave a Comment

BoxofLearn