Rust is a systems programming language that is fast, safe, and memory-efficient. One of the critical features of Rust is its powerful string formatting capabilities.
Rust’s string formatting provides various options to format the strings dynamically which allows us to display the data in multiple ways including numeric values, dates, times, and more.
This tutorial introduces you to Rust’s string formatting features and teaches you how to use them to create the formatted strings.
Prerequisites:
Before you start learning the Rust’s string formatting, you should understand the Rust programming language. If you are new to Rust, you should take some time to familiarize yourself with Rust’s syntax, data types, and control structures.
Additionally, this tutorial assumes that you are using Rust 1.69 or later.
Getting Started
To start with Rust string formatting, you must create a new Rust project. First, open the terminal and use the cargo command to initialize a new project as shown in the following:
The previous command creates a new Rust project named “str_format” with a binary executable file.
After creating the project, we can navigate to the project directory by typing the following command:
We can then proceed to explore the Rust string formatting features.
Rust String Formatting
The simplest way to format a string in Rust is to use the “println!” macro. This macro works similarly to the “printf” function in the C and C-family of programming languages.
The “println!” macro takes a format string and a list of arguments. The format string contains placeholders that define how the arguments should be formatted.
An example is as follows:
let name = "Alice";
let age = 30;
println!("Hello, {}! You are {} years old.", name, age);
}
In the previous example, we use the string formatting feature by adding two placeholder syntax that are denoted by curly braces.
The first placeholder is replaced with the value of the “name” variable, while the second is substituted with the value of the “age” variable.
Once we run the previous code, we should get the following output:
We can use the other types of placeholders to format the different types of data. For example, we can use the “{:x}” placeholder to format an integer as a hexadecimal number:
let num = 255;
println!("The hexadecimal representation of {} is {:x}.", num, num);
}
This should replace the decimal value to a hexadecimal equivalent.
Rust String Formatting Options
Rust’s string formatting provides a wide range of options to customize the data formatting. The following are some examples of string formatting options:
Width and Precision – It allows us to specify the width and precision of the output using the “{:width.precision}” placeholder.
Padding – The padding option allows us to pad the output with zeros or spaces using the “{:0width}” or “{:width}” placeholders, respectively. For example, “{:08}” pads an integer with zeros to a width of 8 characters.
Sign and Alignment – This option enables us to control the sign and the alignment of the output string using “{:+}”, “{:-}”, “{:<}”, “{:^}”, and “{:>}” placeholders. For example, “{:+}” always includes a sign symbol for a numeric value while “{:<}” left-aligns the output.
Octal and Hexadecimal Formatting – It formats an integer as an octal or hexadecimal number using the “{:o}” or “{:x}” placeholders, respectively.
Scientific Notation – It formats the floating-point numbers in scientific notation using the “{:e}” or “{:E}” placeholders.
Date and Time Formatting – Rust provides formatting options to work with date and time values including “{:%Y-%m-%d}” which formats a date in YYYY-MM-DD format.
Formatting the User-Defined Types
We can also format the custom types in Rust by implementing the “std::fmt::Display” trait. This trait provides an “fmt” method that takes a formatter object and formats the value using the provided format string.
struct Person {
name: String,
age: u32,
}
impl fmt::Display for Person {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} ({})", self.name, self.age)
}
}
fn main() {
let person = Person { name: "Alice".to_string(), age: 30 };
println!("Person: {}", person);
}
In the previous example code, the “Person” struct implements the “std::fmt::Display” trait by defining a “fmt” method that writes the name and age of the person to the formatter object.
Running the previous example code should return the following output:
Conclusion
You explored the basics of Rust string formatting. String formatting provides a powerful and flexible way to format the strings dynamically.