DEV Community

Stacy Roll
Stacy Roll

Posted on

2 1 1 1 2

A counter that listen keyboard events 🕹️

How to make a dynamic number counter so that when you press the up arrow, a number is added and when you press the down arrow, a number is subtracted?

I asked myself that question and proceeded to try to solve that algorithm in my mind first and then in code, here is the result.

Let's add the keyboard handler k_board

cargo add k_board

Let's add the program logic:

use k_board::{Keyboard, Keys};

fn main() {
    let mut number: i8 = 0;
    print_number(&mut number, 0);
    for key in Keyboard::new() {
        match key {
            Keys::Up => print_number(&mut number, 1),
            Keys::Down => print_number(&mut number, -1),
            Keys::Enter => break,
            _ => {}
        }
    }
}

fn print_number(number: &mut i8, operation: i8) {
    std::process::Command::new("clear").status().unwrap();
    *number += operation;
    println!("{}", number);
}
Enter fullscreen mode Exit fullscreen mode

See you soon love ❤️

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post