I saw this, and i decided to recreate it without looking at source code. I started rust today because i wanted to learn lower level languages unlike my python, lua, html css and javascript knowledge.
use std::io::{self, Write};
pub fn input(prompt: &str) -> String {
print!("{}", prompt);
io::stdout().flush().unwrap();
let mut line = String::new();
io::stdin().read_line(&mut line).unwrap();
line.trim().to_string()
}
Explanation of Changes
use std::io::{self, Write}; brings the io module into scope so you can write io::stdout() instead of std::io::stdout(). It also imports the Write trait, which provides methods like .flush() and .write_all.
Changed string to prompt as it's more descriptive and accurate
Use the print! macro instead of println! so the input is typed on the same line as the prompt
Use io::stdout().flush() to flush output, which prints it immediately, as Rust buffers output. .unwrap() is used here to handle the Result returned by flush(). if flushing fails, it will panic and stop the program
Remove the String type from line and line.clear() as let mut line = String::new() creates a totally new empty String.
return isn't needed as Rust allows expression-based returns.
line.trim() trims the line and returns a borrowed string slice (&str). .to_string() converts the &str returned by .trim() into an owned String, which is necessary as the function returns a String, not a &str.
You're probably right that python's input doesn't trim normally. I wasn’t really aiming to match python’s behavior exactly, I was just trying to improve the original Rust code a bit. Personally, I think trimming input makes sense in most cases anyway.