Post

Rust Read Input from CLI

Read input from CLI

Create new project using cargo.

Replace content inside main.rs file with following code.

1
2
3
4
5
6
7
8
9
10
11
12
13
use std::io;

fn main() {
    println!("Enter your input");

    let mut cli_input = String::new();

    io::stdin()
        .read_line(&mut cli_input)
        .expect("Failed to read value");

    println!("You entered: {cli_input}");
}

Code explanation

1
use std::io;

Here, we’re importing the io library from Rust standard library. Refer: Rust Standard Library for more information.

1
  println!("Enter your input");

Above code prints a new line on Standard Input with the content given.

1
  let mut cli_input = String::new();

Here we’re creating a mutable variable cli_input with type as String to store the input given by user. Keyword mut indicates that, cli_input is a mutable variable and we can change the value inside it.

For example

1
let count = 10;

Above line creates a new variable count and assign a value 10 to it. In Rust, variables created are immutable by default, meaning, once we create a variable count we can’t alter the value of it, we can use it but can’t change the value.

1
2
  io::stdin()
      .read_line(&mut cli_input)

Here, we’re using stdin function from io module which will allow us to handle user input.

The line .read_line(&mut cli_input) calls read_line method on standard input.

1
  .expect("Failed to read value")

Here, we’re handling potential exceptions thrown by runtime incase of any invalid inputs receved from standard input.

Code

You can refer the github link for full code.

This post is licensed under CC BY 4.0 by the author.