How to get user input?


Hello, so, I’m new here, Rust seems cool and all, but I’m having a bit of a hard time to get user input from the console.

What’s the most easy, straightforward way to get user input from the console without the newline, and also without io:: and :: scattered around all the place, and with the less amout of lines possible?


I would look at for a package: is one example that comes to mind.


Or using only std:

fn main() {
    use std::io::{stdin,stdout,Write};
    let mut s=String::new();
    print!("Please enter some text: ");
    let _=stdout().flush();
    stdin().read_line(&mut s).expect("Did not enter a correct string");
    if let Some('\n')=s.chars().next_back() {
    if let Some('\r')=s.chars().next_back() {
    println!("You typed: {}",s);


First of all, text_io is pure Rust. Putting code in a crate doesn’t make it somehow less Rust. Secondly, your code doesn’t work correctly on Windows (which uses \r\n for newlines). Also, failure on read_line is unlikely to be the user’s fault. It’s not like they can type an entirely arbitrary line of text invalidly.

text_io probably is the absolute simplest way to do this, and I say that as someone with a horse in the race.


They can input something that’s not UTF-8, which AFAICT is the only way read_line will not return Ok. Could be different on Windows.

Edited to address your other concerns.


I’m trying to port some of my C++ code to Rust, and in C++ I just had to do:

string input;
getline(cin, input);
cout << input;


Rust tries to be more correct, but also Rust standard library is rather young still, and some ergonomic concerns will need to be addressed.