Skip to main content

How to take user input from terminal(stdin) in Rust?

In Rust, you can use the std::io module from the standard library to read input from the user. Here's an example that demonstrates how to get input from the user:


use std::io;

fn main() {
    // Create a new instance of `std::io::stdin` for reading user input
    let mut input = String::new();

    // Prompt the user for input
    println!("Enter your name:");

    // Read input from the user
    io::stdin()
        .read_line(&mut input)
        .expect("Failed to read line");

    // Trim any trailing whitespace or newlines from the input
    let name = input.trim();

    // Display the user's input
    println!("Hello, {}!", name);
}

In this example, we create a mutable String variable named input to store the user's input. We then use the std::io::stdin() function to obtain a handle to the standard input stream. Next, we call the read_line() method on the input stream, passing a mutable reference to the input variable. The read_line() method reads input from the user and appends it to the input string.

After reading the input, we can process it as needed. In this example, we trim any trailing whitespace or newlines from the input using the trim() method. Finally, we display a greeting message using the user's input.

It's important to handle potential errors that may occur during the input process. In the example above, the expect() method is used to handle any errors that occur during the read_line() operation. You can customize the error message as needed.

Remember to add use std::io; at the beginning of your file to import the std::io module and make its functions and types available for use.

Certainly! Here's an optimized version of the code that incorporates a few improvements:

use std::io::{self, BufRead};

fn main() {
    // Prompt the user for input
    println!("Enter your name:");

    // Read input from the user
    let stdin = io::stdin();
    let mut input = String::new();
    stdin.lock().read_line(&mut input).expect("Failed to read line");

    // Trim any trailing whitespace or newlines from the input
    let name = input.trim();

    // Display the user's input
    println!("Hello, {}!", name);
} 

In this optimized version:

  1. The use std::io::{self, BufRead}; statement is used to import both std::io and the BufRead trait, which provides additional utility methods for reading lines efficiently.

  2. Instead of creating a separate mutable String variable and then reading input into it, we directly read input into the input variable using the read_line() method. This reduces the need for an extra variable and simplifies the code.

  3. We use stdin.lock().read_line(&mut input) to obtain a locked handle to the standard input stream and read input into the input string. This ensures that multiple threads cannot access the input stream simultaneously, providing safer concurrent access.

These optimizations make the code more concise and efficient while maintaining the functionality of reading user input and displaying the greeting message.

Comments

Popular Posts

Bootstrap Responsive Media Queries CSS Tips

AS a developer I faces lots of problem while making website responsive to make website visible correctly on all devices like mobile, tablet and desktop. So, today I am sharing some Bootstrap responsive CSS styles and Media Queries  tips with you. But make sure that you are not repeating the same media queries for the same screen size. Otherwise it will override your previous CSS style rules.    The Grid Sizes .col-xs-$ => Extra Small (Phones Less than 768px) .col-sm-$ => Small Devices (Tablets 768px and Up) .col-md-$ => Medium Devices (Desktops 992px and Up) .col-lg-$  => Large Devices (Large Desktops 1200px and Up) Here is the Responsive CSS Style for all Screen Sizes Read more: https://scotch.io/tutorials/default-sizes-for-twitter-bootstraps-media-queries

List of latest and most asked PHP practical interviews questions & answers

Core PHP Practical Interview Questions In this blog post I am sharing a list of some most asked PHP interview questions & answers. These are very useful and helpful for the freshers and experienced developer too. I have taken these questions from different sources and listed here at one place. Ques. How to reverse a string without using any builtin function? Ans: <?php $str = 'My name is Diwakar Kumar'; $len = 0; while(isset($str[$len]) != '') $len++; for($i = $len ; $i >= 0 ; $i--) { echo @$str[$i]; } Ques: Write a function to check if a given string is a palindrome or not. Ans: 1st Method: <?php function isPalindrome($str) { $str = strtolower(preg_replace('/[^a-zA-Z0-9]/', '', $str)); // Convert to lowercase and remove non-alphanumeric characters $reverse = strrev($str); // Reverse the string return $str === $reverse; // Compare original and reversed string } 2nd Method: <?php funct

Document and PDF (.doc, .docx and .pdf) file type validation using jQuery

Document and PDF (.doc, .docx and .pdf) file validation using Bootstrap and jQuery Get here reusable file client side validation using Bootstrap and jQuery.