In this article, we will explore the standard input and standard output in the Rust programming language. Generally, the standard input is provided through the keyboard and the standard output displays values in the console.
There are two core traits in Rust, around which the Rust's standard Input and Output are featured. They provide an interface for feeding in input and displaying output. These two traits are listed below:
Let's explore them in detail.
Read Trait:
Reading input from an input device in the form of Bytes is done by Rust components called Readers. The read_line() function is used to read data, one line at a time from an input stream or file. Take a look at the below example:
Example:
Rust
use std::io;
fn main() {
println!("Enter a name:");
let mut guess = String::new();
io::stdin().read_line(&mut guess).expect("failed to readline");
print!("You entered {}", guess);
}
Output:
Same as in other programming languages, we use std::io(standard input/output) library to get input using the read_line function similar to scanf() in C language. The let and mut are keywords to create a mutable variable that can hold the given string.
Write Trait:
The Writers in Rust are programs that can write data to a file or an output stream in bytes. The write() method is used for this purpose. Take a look at the below example.
Example:
Rust
use std::io::Write;
fn main() {
let var1 = std::io::stdout().write("Geeksforgeeks ".as_bytes()).unwrap();
let var2 = std::io::stdout().write(
String::from("is the best.").as_bytes()).unwrap();
std::io::stdout().write(format!(
"\n{} bytes of data has been written!",(var1+var2)).as_bytes()).unwrap();
}
Output:
Geeksforgeeks is the best.
26 bytes of data has been written!
In the above example, the write() function is applied to the standard output stream returned by the stdout() standard library function. An enum is returned by the write() method which is further extracted by the unwrap() function to display the result.
I/O Macros:
The print function is one of the most important and most used to print any output in almost all major programming languages. Rust has and print!() and println!() function similar to printf in C language. We will see how we can print output in Rust. The main difference between Rust's print! & println! is that the print! outputs in the same line whereas println! give output in a new line.
print!
The print macro function of the program is almost similar to cout in C++ without endl (or) \n. An example of print is given below
Example:
Rust
fn main() {
// printed in new line
print!("Hello, Geeks");
print!(" Welcome to GeeksForGeeks");
}
Output:
Hello, Geeks Welcome to GeeksForGeeks
println!
The println is the macro prints to the standard output, with a newline. We can use println! only for the primary output of your program.
Example:
Rust
fn main() {
// printed in new line
println!("Hello, Geeks");
println!("Welcome to GeeksForGeeks");
}
Output:
Hello, Geeks
Welcome to GeeksForGeeks
Reading Input
Same as in other programming languages, we use std::io(standard input/output) library to get input using the read_line function similar to scanf() in C language. The let and mut are keywords to create a mutable variable that can hold the given string.
Rust
use std::io;
fn main() {
println!("Enter a name:");
let mut guess = String::new();
io::stdin().read_line(&mut guess).expect("failed to readline");
print!("You entered {}", guess);
}
Output:
Enter a name: geeksforgeeks
You entered geeksforgeeks
CommandLine Arguments:
Command-line arguments are the values passed through the console to the program for processing. It's similar to how you pass the parameter values to the main() function. The std::env::args() is used to return the command line arguments. Take a look at the below example.
Example:
In this example, we will be using command-line arguments to pass values to the main function of the program.
Rust
use std:: env;
fn main() {
let args: Vec<String> = env::args().collect();
for argument in args.iter() {
println!("{}", argument);
}
}
Let's check what we did in the above example. First, we need to use the environment module using std:: env. Then we create a new vector of strings. Now, this vector just reads each of our arguments. Meaning we can just say the type of the vector is a string that equals a variable and args.collect() function is used to collect the argument from the command line. Here we made a new vector that holds strings this is equal to all the command-line arguments that are collected.
Now use the below command in your shell to activate Rust script:
cargo run
Then pass in the argument as follows:
cargo run YOUR_ARGUMENT
Here we will pass the string "dom" for the sake of example.
Output:
Similar Reads
File I/O in Rust
File I/O in Rust enables us to read from and write to files on our computer. To write or read or write in a file, we need to import modules (like libraries in C++) that hold the necessary functions. This article focuses on discussing File I/O in Rust. Methods for File I/O Given below are some method
7 min read
Scalar Datatypes in Rust
All initialized variables use data-type during declaration to restrict the type of data to be stored. Therefore, we can say that data types are used to tell the variables the type of data they can store. In this article, we will specifically talk about the Scalar Data types in the Rust programming
3 min read
Rust - if let Statement
If-let statement in Rust is an expression that allows pattern matching and is similar to an if expression. Â Once the pattern condition is matched then the block of code is executed. A scrutinee is an expression that is matched during match statement executions. For example match g{ X =>5 , Y =
2 min read
Rust - If-else Statement
Branching with if-else in rust also is similar to other languages. Just the difference is the way of writing(syntax). Here the condition doesn't need to be surrounded by parenthesis. Decision-making structure is an important part of life. Similarly, in programming also there are situations where you
3 min read
Rust - Box<T> Smart Pointer
Box allows us to store data in the heap contrary to the default scheme of Rust to store as a stack. Box is basically used for: For dynamic allocation of memory for variables.When there is a lot of data that we need to transfer ownership and we don't want that they are copied. Let's create a box to s
2 min read
Loops in Rust
A loop is a programming structure that repeats a sequence of instructions until a specific condition is satisfied. Similar to other programming languages, Rust also has two types of loops: Indefinite Loop: While loop and LoopDefinite Loops: For loopLet's explore them in detail. While LoopA simple wa
3 min read
How to Install Rust in MacOS?
Installing Rust on macOS is a straightforward process that allows you to start building fast, memory-efficient applications. This guide will show you how to install Rust using simple commands and set up the Rust programming environment on macOS. Whether you're a beginner or an experienced developer,
3 min read
Variables in Rust
Variables are memory addresses used to store information to be referenced and manipulated in programs. They also provide a way of defining data with a descriptive name, so our programs can be understood more clearly by the reader and ourselves. It is helpful to think of variables as containers that
4 min read
Rust - Formatting Print Statements
In Rust, we use macros to print formatted texts in the editor. Macros provide functionality similar to functions but without the runtime cost. Print statements are used extensively in programming. They are used for prompting users for information or for debugging the program. Macros in Rust end with
3 min read
Rust - From and Into Traits
In Rust, we have the From and Into Traits that are linked internally and are implemented in type, conversion scenarios say in scenarios where we convert from type A to type B. The syntax for From Trait: impl trait From<T>Â {Â Â fn from(T) -> Self;} From traits in Rust are mainly used for eva
3 min read