Lab 3: Introduction to Rust Programming
This lab introduces basic Rust programming concepts.
Variables and Types
// Immutable variable (default)
let x: i32 = 42;
// Type annotation can be omitted
let y = 42; // i32 inferred
// Mutable variable
let mut z = 10;Rust is statically typed with type inference. Unlike dynamically typed languages (Python), variables have fixed types that are known at compile time.
Basic Types
- Integer types:
i8,i16,i32,i64,u8,u16,u32,u64,isize,usize - Floating point:
f32,f64 - Boolean:
bool(values:true,false) - Character:
char(21-bit Unicode Scalar Value)
Compound types:
// Tuple
let t = (4, 'a');
let (a, b) = t; // Destructuring
// Array
let a = [10, 11, 12, 13, 14, 15];
let x = a[2]; // Arrays are bounds-checkedFunctions
fn area(w: i32, h: i32) -> i32 {
w * h // Note: no semicolon - this is an expression that returns a value
}Functions require explicit type annotations for parameters and return values. The last expression (without semicolon) becomes the return value.
Control Flow
// Conditional (if-else as an expression)
let y = if function_returning_boolean() {
42
} else {
7
};
// Loops
loop {
println!("forever");
break; // Use break to exit
}
while x > 0 {
println!("{}", x);
x = x - 1;
}
for e in [10, 20, 30, 40, 50] {
println!("the value is: {}", e);
}Structures and Methods
struct Rectangle {
width: u32,
height: u32
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
}
fn main() {
let rect = Rectangle{width: 30, height: 50};
println!("Area of rectangle is {}", rect.area());
}Enums and Pattern Matching
enum TimeUnit {
Years, Months, Days
}
enum RoughTime {
InThePast(TimeUnit, u32),
JustNow,
InTheFuture(TimeUnit, u32)
}
fn main() {
let when = RoughTime::InThePast(TimeUnit::Years, 87);
match when {
RoughTime::InThePast(units, count) => {
println!("{} time units ago", count)
},
RoughTime::JustNow => {
println!("just now")
},
RoughTime::InTheFuture(units, count) => {
println!("{} time units from now", count)
}
}
}