Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Rust Programming Cookbook

You're reading from   Rust Programming Cookbook Explore the latest features of Rust 2018 for building fast and secure apps

Arrow left icon
Product type Paperback
Published in Oct 2019
Publisher Packt
ISBN-13 9781789530667
Length 444 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Claus Matzinger Claus Matzinger
Author Profile Icon Claus Matzinger
Claus Matzinger
Arrow right icon
View More author details
Toc

Table of Contents (12) Chapters Close

Preface 1. Starting Off with Rust 2. Going Further with Advanced Rust FREE CHAPTER 3. Managing Projects with Cargo 4. Fearless Concurrency 5. Handling Errors and Other Results 6. Expressing Yourself with Macros 7. Integrating Rust with Other Languages 8. Safe Programming for the Web 9. Systems Programming Made Easy 10. Getting Practical with Rust 11. Other Books You May Enjoy

Working with the command line I/O

The traditional way of communicating with the user on the command line is using standard streams. Rust includes helpful macros to deal with these simple cases. In this recipe, we will explore the basic workings of the classic Hello World program.

How to do it...

In just five steps, we will explore command line I/O and formatting:

  1. Open a Terminal window (PowerShell on Windows) and run the cargo new hello-world command, which creates a new Rust project in a hello-world folder.
  2. Once created, change into the directory with cd hello-world and open src/main.rs with a Visual Studio Code. The default code generated by cargo looks like this:
fn main() {
println!("Hello, world!");
}
  1. Let's expand it! These are variations on the preceding traditional print statement, showing some formatting options, parameters, and writing on streams, among other things. Let's start with some common prints (and imports):
use std::io::{self, Write};
use std::f64;

fn main() {
println!("Let's print some lines:");
println!();
println!("Hello, world!");
println!("{}, {}!", "Hello", "world");
print!("Hello, ");
println!("world!");

However, we can do much more complex argument combinations:

    println!("Arguments can be referred to by their position: {0}, 
{1}! and {1}, {0}! are built from the same arguments", "Hello",
"world");

println!("Furthermore the arguments can be named: \"{greeting},
{object}!\"", greeting = "Hello", object = "World");

println!("Number formatting: Pi is {0:.3} or {0:.0} for short",
f64::consts::PI);

println!("... and there is more: {0:>0width$}={0:>width$}=
{0:#x}", 1535, width = 5);

let _ = write!(&mut io::stdout(), "Underneath, it's all writing
to a stream...");
println!();

println!("Write something!");
let mut input = String::new();
if let Ok(n) = io::stdin().read_line(&mut input) {
println!("You wrote: {} ({} bytes) ", input, n);
}
else {
eprintln!("There was an error :(");
}
}

This should provide several variations of reading and writing to the console.

  1. Go back to Terminal and navigate to the directory where Cargo.toml is located.
  2. Use cargo run to see the snippet's output:
$ cargo run
Compiling hello-world v0.1.0 (/tmp/hello-world)
Finished dev [unoptimized + debuginfo] target(s) in 0.37s
Running 'target/debug/hello-world'
Let's print some lines:

Hello, world!
Hello, world!
Hello, world!
Arguments can be referred to by their position: Hello, world! and world, Hello! are built from the same arguments
Furthermore the arguments can be named: "Hello, World!"
Number formatting: Pi is 3.142 or 3 for short
... and there is more: 01535= 1535=0x5ff
Underneath, it's all writing to a stream...
Write something!
Hello, world!
You wrote: Hello, world!
(14 bytes)

Each line in the output represents a way to print text to the console! We recommend playing with the variations and seeing how it changes the result. On a side note, rustc will check for the correct number of arguments in any println!() or format!() call.

Now, let's go behind the scenes to understand the code better.

How it works...

Let's go through the code to understand the execution flow.

cargo is described in depth in Chapter 2, Managing Projects with Cargo, in this book.

The initial snippet is generated when cargo new hello-world is executed in step 1. As a project of type binary, a main function is required and rustc will be looking for it. Upon calling cargo run, cargo orchestrates compilation (with rustc) and linking (msvc on Windows, cc on *nix) and runs the resultant binary via its entry point: the main function (step 5).

In the function we create in step 3, we write a series of print!/println!/eprintln! statements, which are Rust macros. These macros facilitate the writing to the standard output or standard error channels of a command-line application and include additional arguments. In fact, if arguments are missing, the compiler won't compile the program.

Rust's macros work directly on the syntax tree of the language, providing type safety and the ability to check the parameters and arguments. Therefore, they can be seen as a function call with a few special abilities—but more on that in Chapter 6, Expressing Yourself with Macros.

The various arguments and the template string are combined using formatters, a powerful way to add real variables to the output without the need of concatenations or similar workarounds. This will reduce the number of allocations, considerably improving performance and memory efficiency. There is a wide range of how to format data types; to understand it more deeply, check out Rust's excellent documentation (https://doc.rust-lang.org/std/fmt/).

The last step then shows the output that the various combinations produced.

We've successfully learned to work with the command line I/O. Now, let's move on to the next recipe.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime