Alexander Yurchenko

Structs, enums, and error handling in Rust

Created
Updated
Author
Alexander Yurchenko

A malformed ticket ID and a ticket missing from a list call for different actions. Give those outcomes distinct types so callers can tell them apart.

Fields, variants, and visibility

  • struct Ticket groups two fields: a numeric id and a status of type Status. See the chapter on structs.
  • impl Ticket defines operations on the type. The associated function Ticket::from_id runs without an existing ticket. The close method receives one through &mut self and changes its state.
  • enum Status has two variants, Open and Closed. Variants can carry different data, as Some(T) and None do. A match expression must cover every possible value. See the chapter on enums and pattern matching.

A struct resembles a DTO with typed fields in PHP. PHP backed enums associate cases with scalar values. A Rust variant can carry its own fields.

mod tickets declares a module in the same file. pub makes items accessible outside it, and use brings short names into scope. Public fields let other code construct or change these demo tickets directly, so the checks in from_id apply only when that function is called. Rust visibility does not create an HTTP route. See the chapter on modules.

Parse the ID and look up a ticket

Ticket::from_id processes its string in this order:

  1. parse::<u32>() tries to read an unsigned integer.
  2. map_err maps a parsing failure to TicketError::InvalidId.
  3. ? returns a compatible Err early on failure. On success, the expression yields the number.
  4. Zero parses successfully, but the example disallows it as a ticket ID. The function returns TicketError::ZeroId.
  • Result<Ticket, TicketError> holds either Ok(ticket) or Err(error) with the reason for failure. The error appears in the return type. PHP exceptions use a separate control-flow mechanism.
  • Option<&Ticket> holds Some(ticket) with a reference, or None if the search finds nothing. It serves a similar purpose to a nullable PHP type. The Some variant can hold a borrowed value.

See the chapter on error handling. A web handler could map a malformed parameter and a missing record to different responses. This example uses fixed strings and an in-memory list.

Run the program and its test

Open the Cargo demo project, replace the entire src/main.rs, then run cargo run and cargo test. The test covers closing a ticket, both lookup outcomes, and both errors. The {:?} placeholder uses Debug for terminal output. An HTTP response needs its own representation.

RUST
mod tickets {
    #[derive(Debug, PartialEq)]
    pub enum Status {
        Open,
        Closed,
    }

    #[derive(Debug, PartialEq)]
    pub enum TicketError {
        InvalidId,
        ZeroId,
    }

    pub struct Ticket {
        pub id: u32,
        pub status: Status,
    }

    impl Ticket {
        pub fn from_id(input: &str) -> Result<Self, TicketError> {
            let id = input.parse::<u32>().map_err(|_| TicketError::InvalidId)?;
            // Zero parses successfully but is disallowed by the ticket ID rule.
            if id == 0 {
                return Err(TicketError::ZeroId);
            }
            Ok(Self { id, status: Status::Open })
        }

        pub fn close(&mut self) {
            self.status = Status::Closed;
        }
    }

    // The matching ticket stays in the collection, so return a reference to it.
    pub fn find(tickets: &[Ticket], id: u32) -> Option<&Ticket> {
        tickets.iter().find(|ticket| ticket.id == id)
    }
}

use tickets::{Ticket, find};

fn main() {
    let mut tickets = Vec::new();
    for input in ["42", "bad", "0"] {
        match Ticket::from_id(input) {
            Ok(mut ticket) => {
                ticket.close();
                println!("{}: {:?}", ticket.id, ticket.status);
                tickets.push(ticket);
            }
            Err(error) => println!("{}: {:?}", input, error),
        }
    }
    match find(&tickets, 42) {
        Some(ticket) => println!("found: {}", ticket.id),
        None => println!("not found"),
    }
    match find(&tickets, 99) {
        Some(ticket) => println!("found: {}", ticket.id),
        None => println!("not found"),
    }
}

#[cfg(test)]
mod tests {
    use super::tickets::{Status, Ticket, TicketError, find};

    #[test]
    fn distinguishes_valid_missing_and_invalid() {
        let mut ticket = match Ticket::from_id("42") {
            Ok(ticket) => ticket,
            Err(error) => panic!("unexpected error: {:?}", error),
        };
        assert_eq!(ticket.status, Status::Open);
        ticket.close();
        assert_eq!(ticket.status, Status::Closed);
        let tickets = [ticket];
        assert_eq!(find(&tickets, 42).map(|ticket| ticket.id), Some(42));
        assert!(find(&tickets, 99).is_none());
        assert!(matches!(Ticket::from_id("bad"), Err(TicketError::InvalidId)));
        assert!(matches!(Ticket::from_id("0"), Err(TicketError::ZeroId)));
    }
}

TEXT
42: Closed
bad: InvalidId
0: ZeroId
found: 42
not found

Summary

The return type tells callers which outcomes they need to handle. The reference returned by find also depends on the original collection. The lesson on ownership and borrowing explains that relationship.