COMP3007 - Modern Programming Languages
Week 8: Rust - Advanced Topics
Dr. Öğr. Üyesi Yusuf Kürşat Tuncel
Department of Computer Engineering
Fall 2024-2025
Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department
COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 1 / 31
Outline
1 Advanced Traits
2 Advanced Types
3 Advanced Functions and Closures
4 Macros
5 Unsafe Rust
6 Advanced Lifetime Concepts
7 Advanced Pattern Matching
8 Advanced Generics
9 Advanced Concurrency
10 Advanced Error Handling
11 Advanced Cargo Features
12 WebAssembly with Rust
13 Conclusion and Next Steps
Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department
COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 2 / 31
Associated Types
1 pub trait Iterator {
2 type Item;
3 fn next (& mut self) -> Option <Self ::Item >;
4 }
Associated types connect a type placeholder with a trait
Allows for more flexible and reusable trait definitions
Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department
COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 3 / 31
Default Generic Type Parameters
1 trait Add <RHS=Self > {
2 type Output ;
3 fn add(self , rhs: RHS) -> Self :: Output ;
4 }
Allows specification of a default concrete type for the generic type
Useful for extending functionality without breaking existing code
Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department
COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 4 / 31
Fully Qualified Syntax
1 trait Animal {
2 fn baby_name () -> String ;
3 }
4
5 struct Dog;
6
7 impl Dog {
8 fn baby_name () -> String {
9 String :: from("Spot")
10 }
11 }
12
13 impl Animal for Dog {
14 fn baby_name () -> String {
15 String :: from(" puppy ")
16 }
17 }
18
19 fn main () {
Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department
COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 5 / 31
Newtype Pattern
1 struct Millimeters (u32);
2 struct Meters (u32);
Creates a new type in a tuple struct
Useful for adding semantic meaning to a type
Can be used to implement traits on external types
Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department
COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 6 / 31
Type Aliases
1 type Kilometers = i32;
2
3 let x: i32 = 5;
4 let y: Kilometers = 5;
5
6 println !("x + y = {}", x + y);
Creates an alias for an existing type
Useful for reducing repetition of long type names
Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department
COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 7 / 31
The Never Type
1 fn bar () -> ! {
2 panic !("This call never returns .");
3 }
The ! type, pronounced ”never”, is the empty type
Used for functions that never return
Examples: panic!, loop, etc.
Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department
COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 8 / 31
Function Pointers
1 fn add_one (x: i32) -> i32 {
2 x + 1
3 }
4
5 fn do_twice (f: fn(i32) -> i32 , arg: i32) -> i32 {
6 f(arg) + f(arg)
7 }
8
9 fn main () {
10 let answer = do_twice (add_one , 5);
11 println !("The answer is: {}", answer );
12 }
Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department
COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 9 / 31
Returning Closures
1 fn returns_closure () -> Box <dyn Fn(i32) -> i32 > {
2 Box :: new (|x| x + 1)
3 }
Closures are represented by traits, so we need to use a trait object
Box is used to get a sized value
Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department
COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 10 / 31
Declarative Macros
1 macro_rules ! vec {
2 ( $( $x:expr ) ,* ) => {
3 {
4 let mut temp_vec = Vec :: new ();
5 $(
6 temp_vec .push($x);
7 )*
8 temp_vec
9 }
10 };
11 }
Allow you to write code that writes other code (metaprogramming)
Useful for reducing repetition of code
Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department
COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 11 / 31
Procedural Macros
1 use proc_macro ;
2
3 #[ some_attribute ]
4 pub fn some_name (input: TokenStream ) -> TokenStream {
5 }
Three kinds: custom derive, attribute-like, function-like
More powerful than declarative macros, but more complex
Operate on Rust code represented as token streams
Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department
COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 12 / 31
Unsafe Rust
Allows you to opt out of some of Rust’s guarantees
Gives you more power, but with great responsibility
Five main things you can do in unsafe Rust:
Dereference a raw pointer
Call an unsafe function or method
Access or modify a mutable static variable
Implement an unsafe trait
Access fields of unions
Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department
COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 13 / 31
Example of Unsafe Code
1 let mut num = 5;
2
3 let r1 = &num as *const i32;
4 let r2 = &mut num as *mut i32;
5
6 unsafe {
7 println !("r1 is: {}", *r1);
8 *r2 = 10;
9 println !("r2 is: {}", *r2);
10 }
Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department
COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 14 / 31
Lifetime Subtyping
1 struct Parser <'a> {
2 content : &'a str ,
3 }
4
5 impl <'a> Parser <'a> {
6 fn parse <'b>(&'b self) -> Result <() , &'b str >
7 where
8 'a: 'b
9 {
10 // parsing logic here
11 }
12 }
Specifies that one lifetime outlives another
Useful in complex scenarios involving multiple lifetimes
Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department
COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 15 / 31
Lifetime Bounds
1 use std :: fmt :: Display ;
2
3 fn longest_with_an_announcement <'a, T>(
4 x: &'a str ,
5 y: &'a str ,
6 ann: T,
7 ) -> &'a str
8 where
9 T: Display ,
10 {
11 println !(" Announcement ! {}", ann);
12 if [Link] () > [Link] () {
13 x
14 } else {
15 y
16 }
17 }
Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department
COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 16 / 31
Match Guards
1 let num = Some (4);
2
3 match num {
4 Some(x) if x < 5 => println !("less than five: {}",
x),
5 Some(x) => println !("{}", x),
6 None => (),
7 }
Match guards allow for additional if conditions in match arms
Useful for more complex matching scenarios
Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department
COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 17 / 31
@ Bindings
1 enum Message {
2 Hello { id: i32 },
3 }
4
5 let msg = Message :: Hello { id: 5 };
6
7 match msg {
8 Message :: Hello { id: id_variable @ 3..=7 } => {
9 println !("Found an id in range : {}", id_variable )
10 },
11 Message :: Hello { id: 10..=12 } => {
12 println !("Found an id in another range ")
13 },
14 Message :: Hello { id } => {
15 println !("Found some other id: {}", id)
16 },
17 }
Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department
COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 18 / 31
Const Generics
1 struct ArrayWrapper <T, const N: usize > {
2 array: [T; N],
3 }
4
5 fn main () {
6 let wrapper = ArrayWrapper { array: [1, 2, 3, 4, 5]
};
7 }
Allows for generics over constant values
Useful for creating more flexible array types
Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department
COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 19 / 31
Trait Bounds with Associated Types
1 trait Container {
2 type Item;
3 fn insert (& mut self , item: Self :: Item);
4 fn remove (& mut self) -> Option <Self ::Item >;
5 }
6
7 fn process <T: Container <Item = i32 >>( container : &mut T) {
8 // Process a container of i32s
9 }
Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department
COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 20 / 31
Atomics
1 use std :: sync :: atomic :{ AtomicI32 , Ordering };
2 use std :: sync :: Arc;
3 use std :: thread ;
4
5 fn main () {
6 let counter = Arc :: new( AtomicI32 :: new (0));
7 let mut handles = vec ![];
8
9 for _ in 0..10 {
10 let counter = Arc :: clone (& counter );
11 let handle = thread :: spawn(move || {
12 counter . fetch_add (1, Ordering :: SeqCst );
13 });
14 handles .push( handle );
15 }
16
17 for handle in handles {
18 handle .join (). unwrap ();
19 }
Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department
COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 21 / 31
Rayon for Parallel Iteration
1 use rayon :: prelude ::*;
2
3 fn sum_of_squares (input: &[ i32 ]) -> i32 {
4 input. par_iter ()
5 .map (|&i| i * i)
6 .sum ()
7 }
8
9 fn main () {
10 let v = vec ![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
11 println !("Sum of squares : {}", sum_of_squares (&v));
12 }
Rayon is a data parallelism library for Rust
Allows for easy parallelization of computations
Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department
COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 22 / 31
Custom Error Types
1 use std :: fmt;
2 use std :: error :: Error;
3
4 #[ derive (Debug)]
5 struct AppError {
6 kind: String ,
7 message : String ,
8 }
9
10 impl fmt :: Display for AppError {
11 fn fmt (& self , f: &mut fmt :: Formatter ) -> fmt :: Result
{
12 write !(f, "{}: {}", [Link] , self. message )
13 }
14 }
15
16 impl Error for AppError {}
17
18 fn main () -> Result <() , Box <dyn Error >> {
Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department
COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 23 / 31
Error Context with anyhow
1 use anyhow :{ Context , Result };
2 use std ::fs:: File;
3 use std ::io:: Read;
4
5 fn read_file_contents (path: &str) -> Result <String > {
6 let mut file = File :: open(path)
7 . with_context (|| format !(" failed to open file
`{}`", path))?;
8 let mut contents = String :: new ();
9 file. read_to_string (& mut contents )
10 . with_context (|| format !(" failed to read file
`{}`", path))?;
11 Ok( contents )
12 }
13
14 fn main () -> Result <() > {
15 let contents =
read_file_contents (" nonexistent .txt")?;
16 println !("{}", contents );
Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department
COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 24 / 31
Cargo Features
Conditional compilation with features
In [Link]:
1 [ features ]
2 default = [" console_error_panic_hook "]
3 console_error_panic_hook =
["dep: console_error_panic_hook "]
4
5 [ dependencies ]
6 console_error_panic_hook = { version = " 0.1.7 ", optional
= true }
In code:
1 #[ cfg( feature = " console_error_panic_hook ")]
2 use console_error_panic_hook :: set_once as set_panic_hook ;
Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department
COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 25 / 31
Introduction to WebAssembly
WebAssembly (Wasm) is a binary instruction format for a stack-based
virtual machine
Designed as a portable target for high-level languages like Rust
Allows running Rust code in web browsers at near-native speed
Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department
COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 26 / 31
Simple Rust to WebAssembly Example
1 // [Link]
2 use wasm_bindgen :: prelude ::*;
3
4 #[ wasm_bindgen ]
5 pub fn fibonacci (n: u32) -> u32 {
6 if n <= 1 {
7 return n;
8 }
9 let mut a = 0;
10 let mut b = 1;
11 for _ in 2..=n {
12 let temp = a + b;
13 a = b;
14 b = temp;
15 }
16 b
17 }
18
19 // JavaScript
Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department
COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 27 / 31
Conclusion
We’ve covered a wide range of advanced Rust topics
These features allow for powerful, safe, and efficient programming
Practice and real-world projects are key to mastering these concepts
Rust’s ecosystem is constantly evolving, stay updated!
Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department
COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 28 / 31
Key Takeaways
Advanced Rust features provide powerful tools for complex scenarios
Traits and associated types allow for flexible and reusable code
Advanced types like newtypes and type aliases improve code semantics
Macros enable metaprogramming capabilities
Unsafe Rust provides escape hatches when necessary
Advanced lifetime concepts allow for fine-grained control over
references
These features should be used judiciously to maintain code clarity
Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department
COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 29 / 31
Next Steps
Explore Rust’s rich ecosystem of libraries (crates)
Contribute to open-source Rust projects
Stay updated with the Rust blog and release notes
Next week, we’ll start our exploration of Go!
Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department
COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 30 / 31
Thank You! Any Questions?
Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department
COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 31 / 31