Home

Programming With Rust

A small Rust project and programming concepts.

Overview

In this project I built a small ticket tracker in Rust to demonstrate and practise some fundamental programming concepts while also putting my passive knowledge of programming languages, Rust here in particular, to use. This program will store a collection of tickets, display their state, and allow individual tickets to be marked as fixed.

Ticket Representation

Each ticket is represented using a struct:

struct Ticket {
    number: u32,
    description: String,
    is_fixed: bool,
}           

Structs are used for grouping related data into a single type. In this example, every ticket here contains an ID number, a description, and a boolean representing whether the ticket has been "fixed". The description value is stored as a String, this allows each ticket to have ownership of their text.

To make creating tickets simpler and more consistent, I added an associated ::new() function for my newly created type:

impl Ticket {
    fn new(number: u32, description: String) -> Ticket {
        Ticket {
            number,
            description,
            is_fixed: false,
        }
    }
}           

Thus allowing me to create a Ticket more conveniently with Ticket::new(), this also ensures that every newly created Ticket begins with the is_fixed boolean set to false.

Methods and Borrowing

Here I added some methods inside impl to "fix" and print each ticket's values:

fn fix(&mut self) {
    self.is_fixed = true;
}

fn print(&self) {
    println!("#{} | {} | Fixed? {}",
        self.number,
        self.description,
        self.is_fixed
    );
}           

The two methods here will also demonstrate the difference between immutable and mutable borrowing in Rust. print() uses &self because of its need to only read the ticket, while fix() uses &mut self since it needs to change the value of is_fixed. In short: &self has read-only access, whilst &mut self has permission to modify; this is all while the ticket being borrowed is still being owned by the code that created it; the methods used here only borrow access for as long as is needed.

A Collection of Tickets

Here I store the tickets in a vector:

let mut tickets: Vec<Ticket> = Vec::new();

Vec<Ticket> is a growable collection that contains Ticket values. The vector itself is also mutable, as we will be pushing new tickets to it during the program.

To display all the stored tickets in the collection, I pass the collection to a function and then have it iterate over its contents:

fn print_tickets(tickets: &[Ticket]) {
    for ticket in tickets {
        ticket.print();
    }
}           

This function only needs to read the tickets, therefore only requiring an immutably borrowed slice rather than a mutable one.

And contrasting the immutably borrowed slice, is this mutably borrowed one:

fn fix_ticket(tickets: &mut [Ticket], number: u32) {
    for ticket in tickets {
        if ticket.number == number {
            ticket.fix();
            return;
        }
    }

    println!("Can't find ticket!");
}           

This function will check each ticket until it finds the matching number. Once the number has been found, it will call the fix method and return immediately. However, if the loop finishes and does not find a match, the program reports that the ticket could not be found.

Next I added a count function, utilising the previous concepts:

fn count_fixed(tickets: &[Ticket]) -> usize {
    let mut count = 0;

    for ticket in tickets {
        if ticket.is_fixed {
            count += 1;
        }
    }

    count
}

An interesting thing you can see here is count lacking a semicolon. In Rust, blocks can return the value of the final expression without a explicit return keyword. So in this case, the value of count becomes count_fixed()'s return value.

Lastly I added an edit function, to edit the description of a ticket utilising mutable borrowing again:

fn edit_ticket(tickets: &mut [Ticket], number: u32, description: String) {
    for ticket in tickets {
        if ticket.number == number {
            ticket.description = description;
            return;
        }
    }
}

Putting Everything Together

An empty vector is created using Vec::new() and tickets will be one-by-one pushed into it:

let mut tickets: Vec<Ticket> = Vec::new();

tickets.push(Ticket::new(
    1,
    String::from("wifi isnt working!!")
));
tickets.push(Ticket::new(
    2,
    String::from("browser wont open")
));
tickets.push(Ticket::new(
    3,
    String::from("the printer's doing it again")
));         

Then the same created collection, can be borrowed differently depending on what the program will require:

println!("Tickets before:");
print_tickets(&tickets);

fix_ticket(&mut tickets, 2);
edit_ticket(&mut tickets, 3, String::from("the printer's broken"));
println!("~~~~~~~~~~~~~~");

println!("Tickets after:");
print_tickets(&tickets);

println!("~~~~~~~~~~~~~~");
println!("Total fixed: {}", count_fixed(&tickets));

Here, print_tickets(&tickets) and count_fixed(&tickets) only need to borrow the collection for reading, whereas fix_ticket(&mut tickets, u32) and edit_ticket(&mut tickets, u32, String) receive a mutable borrow, thus allowing changes to the stored Tickets inside tickets.

Finally, running the program will demonstrate the second ticket's state change, and third ticket's description change with a before and after; and then printing total is_fixed tickets:

Tickets before:
#1 | wifi isnt working!! | Fixed? false
#2 | browser wont open | Fixed? false
#3 | the printer's doing it again | Fixed? false
~~~~~~~~~~~~~~
Tickets after:
#1 | wifi isnt working!! | Fixed? false
#2 | browser wont open | Fixed? true
#3 | the printer's broken | Fixed? false
~~~~~~~~~~~~~~
Total fixed: 1

Takeaways

This project and my recent general study solidified a lot of programming concepts I had floating around in my head for years, i.e., completed a few internet C, Python, JavaScript, Java (etc.) courses.

Here and recently I was able to solidify what I knew and actually apply that knowledge to something tangible, while also learning about Rust's interesting features such as borrowing and ownership.