Introduction to Rust
Rust is a systems programming language with an emphasis on memory safety, performance and concurrency. In this practical, you will investigate its basic syntax and the features that distinguish it from C.
Practical Checklist
1. Variables and mutability
Rust variables are immutable by default: once initialised, their value cannot be reassigned. Add mut when reassignment is required.
-
Read the following example and identify which variable may be reassigned.
#![allow(unused)] fn main() { let x = 5; /* immutable*/ let mut y = 10; /* mutable*/ y = 15; /* allowed because y is mutable*/ }
2. Data types
Rust has both scalar types (one value) and compound types (values grouped together). Explicit type annotations are useful when the type cannot be inferred or when an exact numeric representation matters.
Scalar types
| Type | Description | Example |
|---|---|---|
| Integers | Signed or unsigned whole numbers | i32, u32, i64, u64 |
| Floating-point | Real-number approximations | f32, f64 |
| Boolean | Logical values | bool |
| Character | One Unicode scalar value | char |
-
Examine the type annotation on each declaration.
#![allow(unused)] fn main() { let a: i32 = 100; let b: f64 = 3.14; let c: bool = true; let d: char = 'R'; } -
Identify which types are signed, which can store a fraction, and which represent logical or textual values.
Compound types
Tuples group values of potentially different types; arrays have a fixed length and contain values of one type.
-
Compare the tuple and array declarations below.
#![allow(unused)] fn main() { let tup: (i32, f64, char) = (500, 3.14, 'R'); let arr: [i32; 3] = [1, 2, 3]; }
3. Control flow
Rust provides if/else, loop, while and for. A condition must evaluate to a bool; integers are not implicitly treated as Boolean values.
-
Examine the condition, loop and range in the following source.
#![allow(unused)] fn main() { /* If-else */ let number = 6; if number % 2 == 0 { println!("Even"); } else { println!("Odd"); } /* Loop */ let mut counter = 0; loop { counter += 1; if counter == 5 { break; } } /* For loop */ for i in 0..5 { println!("{}", i); } } -
Predict which messages would be printed and the final value of
counter.
4. Functions
Functions are introduced using fn. Parameter types are declared explicitly, as is the return type when the function returns a value.
-
Identify the parameters, return type, and returned expression in
add.#![allow(unused)] fn main() { fn add(a: i32, b: i32) -> i32 { a + b } let result = add(3, 4); println!("Sum is: {}", result); }
5. Ownership and borrowing
Rust’s ownership system manages memory without requiring a garbage collector. A value has an owner; borrowing allows another part of the programme to access the value without taking ownership.
-
Run the code in here:
fn main() { let s1 = String::from("hello"); let s2 = &s1; /* Immutable borrow */ println!("{}", s2); } -
Identify the owner of the
Stringand the immutable borrower. -
Test the immutable borrow, we should get an error
[E0502]fn main() { let mut s1 = String::from("hello"); let s2 = &s1; /* Immutable borrow*/ s1.push_str(" world"); /* Error: mutable access while borrowed*/ println!("{}", s2); }
6. Keywords and language constructs
| Keyword | Purpose |
|---|---|
let, mut | Bind values and allow reassignment |
fn | Define a function |
if, else, while, for, loop | Control execution |
match | Match a value against patterns |
struct, enum | Define data structures and variants |
impl | Define associated methods and functions |
mod | Define a module |
7. Pattern matching and Option
Rust uses match to select behaviour according to patterns. Option<T> represents either a present value (Some) or an absent value (None). It avoids representing an absent value with an arbitrary sentinel.
-
Identify the two possible cases handled by this example.
#![allow(unused)] fn main() { let result = Some(10); match result { Some(x) => println!("Found: {}", x), None => println!("Not found"), } } -
Explain which branch executes when
resultcontainsSome(10)and what would happen forNone.