DEV Community

Stacy Roll
Stacy Roll

Posted on

How to make a dynamic menu in rust ๐Ÿ“ƒ

In this article I am going to show you how to make a dynamic menu in Rust. First of all, let's add a lightweight keyboard event handler, I'll use k_board.

cargo add k_board

Then let's put together the program logic and match the results after receiving the enter as a parameter.

use std::io::Write; fn main() { let mut option: u8 = 0; show_option('*', ' '); for key in k_board::Keyboard::new() { match key { k_board::Keys::Up => option = 0 , k_board::Keys::Down => option = 1, k_board::Keys::Enter => break, _ => {} } match option { 0 => show_option('*', ' '), 1 => show_option(' ', '*'), _ => {} } } clear_screen(); println!("Enter the text you want to print"); let mut text: String = String::new(); let _ = std::io::stdout().flush(); std::io::stdin().read_line(&mut text).expect("Error"); clear_screen(); match option { 0 => { println!("{}", text); } 1 => unsafe { printf("%s\0".as_ptr(), text.as_ptr()); }, _ => {} } } fn clear_screen() { std::process::Command::new("clear").status().unwrap(); } fn show_option(op1: char, op2: char) { clear_screen(); println!( "{} print in RUST\n{} print in C", op1, op2 ); } extern "C" { fn printf(format: *const u8, ...) -> i32; } 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)