Get the input in Rust

Get the input in Rust

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

Get the input
Rust
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 *

How to whitelist website on AdBlocker?

How to whitelist website on AdBlocker?

  1. 1 Click on the AdBlock Plus icon on the top right corner of your browser
  2. 2 Click on "Enabled on this site" from the AdBlock Plus option
  3. 3 Refresh the page and start browsing the site
%d bloggers like this: