Get the input in Rust

Get the input in Rust

Rust
Rust

I started learning Rust lately. Kind of interesting but more to learn. Here is the program that help in getting the input from user in console. I am sure this might help you.

fn main() {
    print!("Please enter some text: ");
    let input=get_input(); 
    println!("Input = {0}", input);
}

The following code defines how you write functions.

fn get_input() -> String { return someString;}

Below is the function to get input from the stream and return as string.

fn get_input() -> String {
    use std::io::{stdin,stdout,Write};
    let mut s=String::new();
    let _=stdout().flush();
    stdin().read_line(&mut s).expect("Did not enter a correct string");
    if let Some('\n')=s.chars().next_back() {
        s.pop();
    }
    if let Some('\r')=s.chars().next_back() {
        s.pop();
    }
   return s;
}

Click here to view my github gist

See other posts on RUST

Leave a Reply

Your email address will not be published. Required fields are marked *

Please disable your adblocker or whitelist this site!

%d bloggers like this: