A crate that makes getting command line input easy


#1

read_input

I have spent some time helping young people get started with programming in rust. When helping people I found that getting user input in the command line was not very easy for a beginner and involved lots of complexity that was hard to explain.

I decided to use rusts trait system to make user input easier to understand and use. After many code reviews on Discord, the project started to look and work exactly as I wanted.

Not only does my crate make things easier for new rustaceans but also makes life easier for other more complex command line tools.

Please reply with any feedback.


#2

Nice ! How does it compare to rustyline ?


#3

rustyline and read_input are very different.

rustyline seems to be for autocompletion mainly while read_input does not offer autocompletion.

read_input simply makes getting user input while the program is running in a command prompt easier using std:io.

let input = loop {
    let mut input = String::new();

    io::stdin()
        .read_line(&mut input)
        .expect("Failed to read line");

    break match input.trim().parse::<i32>() {
        Ok(num) => num,
        Err(_) => continue,
    };
};

becomes

let input: i32 = input_new().get(); 

this pattern also has a large number of extra features that you can read about in the readme file.


#4

By the way, thanks for the loop { ... break match {... => continue } } pattern. Seems I’m missing something with this syntax yet…


#5

In rust 2018 loops can break with a value.

So with

let input = loop { ... }

the input variable becomes whatever the loop breaks with.

With break match { ... };, the loop returns with whatever the match expression returns.

The continue branch of the match never returns as it goes back to the start of the loop.


#6

Ok I get it. I was just wondering if line-editing code could be factorized (mainly for harmonizing their behaviors).
Anyway thank for this crate, it looks useful.