Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rust: Create editable CLI input

Tags:

rust

To read user input in rust, we can do this:

use std::io;
let mut input = String::new();
print!("Edit username: ");
io::stdout().flush().ok();
io::stdin().readline(&mut input);

What I want is a way to create editable input text, like filling the stdin with some text that the user can edit. Something like this:

  stdout              stdin
     |                  |
Edit username: <existing username>
like image 514
plutolaser Avatar asked Sep 11 '26 00:09

plutolaser


1 Answers

If you are OK with using an external crate, and you don't need the full terminal UI capabilities of something like tui (which depends on termion or crossterm), you can use rustyline.

use rustyline::{DefaultEditor, Result};

fn main() -> Result<()> {
    let mut rl = DefaultEditor::new()?;
    const DEFAULT_USERNAME: &str = "admin";
    let input = rl.readline_with_initial("Edit username: ", (DEFAULT_USERNAME, ""))?;
    println!("Your selected username: {input}");
    Ok(())
}

enter image description here enter image description here enter image description here

Credit to this answer (How do I enable editable user input for a Rust terminal application?)

like image 104
Tigregalis Avatar answered Sep 12 '26 18:09

Tigregalis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!