Book Image

Rust Standard Library Cookbook

By : Jan Hohenheim, Daniel Durante
Book Image

Rust Standard Library Cookbook

By: Jan Hohenheim, Daniel Durante

Overview of this book

Mozilla’s Rust is gaining much attention with amazing features and a powerful library. This book will take you through varied recipes to teach you how to leverage the Standard library to implement efficient solutions. The book begins with a brief look at the basic modules of the Standard library and collections. From here, the recipes will cover packages that support file/directory handling and interaction through parsing. You will learn about packages related to advanced data structures, error handling, and networking. You will also learn to work with futures and experimental nightly features. The book also covers the most relevant external crates in Rust. By the end of the book, you will be proficient at using the Rust Standard library.
Table of Contents (12 chapters)

How to do it...

  1. In the src/bin folder, create a file called format.rs
  2. Add the following code and run it with cargo run --bin format
1  fn main() {
2 let colour = "red";
3 // The '{}' it the formatted string gets replaced by the
parameter
4 let favourite = format!("My favourite colour is {}", colour);
5 println!("{}", favourite);
6
7 // You can add multiple parameters, which will be
8 // put in place one after another
9 let hello = "hello ";
10 let world = "world!";
11 let hello_world = format!("{}{}", hello, world);
12 println!("{}", hello_world); // Prints "hello world!"
13
14 // format! can concatenate any data types that
15 // implement the 'Display' trait, such as numbers
16 let favourite_num = format!("My favourite number is {}", 42);
17 println!("{}", favourite_num); // Prints "My favourite number
is 42"
18
19 // If you want to include certain parameters multiple times
20 // into the string, you can use positional parameters
21 let duck_duck_goose = format!("{0}, {0}, {0}, {1}!", "duck",
"goose");
22 println!("{}", duck_duck_goose); // Prints "duck, duck, duck,
goose!"
23
24 // You can even name your parameters!
25 let introduction = format!(
26 "My name is {surname}, {forename} {surname}",
27 surname="Bond",
28 forename="James"
29 );
30 println!("{}", introduction) // Prints "My name is Bond, James
Bond"
31 }