DEV Community

Stacy Roll
Stacy Roll

Posted on

Queues in rust: enqueue and dequeue 👉

In C, queues are elements that we can easily handle with pointers. In Rust, we have VecDeque included in the standard library, which allows us to manage queues of elements in a simple and easy way. Here's an example:

cargo add k_board

use k_board::{Keyboard, Keys};
use std::collections::VecDeque;

fn main() {
    let mut queue: VecDeque<i32> = VecDeque::new();
    loop {
        let mut option = menu(0);
        for key in Keyboard::new() {
            match key {
                Keys::Up => option = menu(0), // add to queue
                Keys::Down => option = menu(1), // clear queue
                Keys::Enter => break,
                _ => {}
            }
        }
        match option {
            0 => add_to_queue(&mut queue),
            1 => clear_queue(&mut queue),
            _ => {}
        }
    }
}

fn menu(operation: u8) -> u8 {
    std::process::Command::new("clear").status().unwrap();
    let mut op: Vec<char> = vec!['*', ' '];
    if operation == 1 {
        op[0] = ' ';
        op[1] = '*';
    }
    println!(
        "{} Add a number to the queue\n{} Free all queue memory",
        op[0], op[1]
    );
    operation
}

fn add_to_queue(queue: &mut VecDeque<i32>) {
    queue.push_back(get_number());
    println!("Elements in the queue: {:?}", queue);
    look_output();
}

fn get_number() -> i32 {
    println!("Enter a number to the queue");
    let mut input: String = String::new();
    std::io::stdin().read_line(&mut input).expect("Error");
    let number: i32 = match input.trim().parse() {
        Ok(number) => number,
        Err(_) => get_number(),
    };
    number
}

fn clear_queue(queue: &mut VecDeque<i32>) {
    queue.clear();
    println!("Queue after clear: {:?}", queue);
    look_output();
}

fn look_output() {
    let mut look_output: String = String::new();
    std::io::stdin().read_line(&mut look_output).expect("Error");
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)