DEV Community

Stacy Roll
Stacy Roll

Posted on

1

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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more