Python input function rewritten in rust

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.

pub fn input(string:&str)->String{
    println!("{}",string);
    let mut line:String=String::new();
    line.clear();
    std::io::stdin()
        .read_line(&mut line).unwrap();
    return line;
}

1 Like

Here is an improved version of your code:

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

  1. 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.
  2. Changed string to prompt as it's more descriptive and accurate
  3. Use the print! macro instead of println! so the input is typed on the same line as the prompt
  4. 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
  5. Remove the String type from line and line.clear() as let mut line = String::new() creates a totally new empty String.
  6. return isn't needed as Rust allows expression-based returns.
  7. 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.
2 Likes

python input does not trim.

1 Like

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.

2 Likes

I was going for pythons type of input, also @Pjdur and @Bruecki thank you for replying, im trying rust for the first time

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.