format! Macro
Part of the Fundamentals section of Coddy's Rust journey — lesson 70 of 75.
In Rust, the format! macro allows you to combine text with variables in a readable and customizable way. This macro is similar to println!, but instead of printing the output to the console, it returns a formatted string that you can store in a variable or use in other operations.
The simplest syntax uses unnamed placeholders {}:
let name = "Alice";
let age = 30;
let formatted = format!("Name: {}, Age: {}", name, age);
println!("{}", formatted);
// Output: Name: Alice, Age: 30You can use variable names directly in the placeholders:
let name = "Bob";
let age = 25;
let formatted = format!("Name: {name}, Age: {age}");
println!("{}", formatted);
// Output: Name: Bob, Age: 25You can specify the position of arguments using numbers:
let formatted = format!("{1} {0} {2}", "first", "second", "third");
println!("{}", formatted);
// Output: second first thirdYou can control how values are formatted using format specifiers:
// Number formatting
let pi = 3.1415926;
let formatted_float = format!("{:.2}", pi);
// "3.14"
// Padding with zeros
let padded = format!("{:0>5}", "123");
// "00123"Challenge
EasyCreate a program that generates a secret code from a name and birth year using these exact rules:
- Takes the first letter of the name and makes it uppercase
- Reverses the year digits
- Wraps the first letter with "⭐" symbols
- Adds a "-" between the wrapped letter and reversed year
To reverse a string use the following code: .to_string().chars().rev().collect::<String>()
Cheat sheet
The format! macro combines text with variables and returns a formatted string that can be stored in a variable.
Basic syntax with unnamed placeholders:
let name = "Alice";
let age = 30;
let formatted = format!("Name: {}, Age: {}", name, age);Using variable names directly in placeholders:
let name = "Bob";
let age = 25;
let formatted = format!("Name: {name}, Age: {age}");Specifying argument positions with numbers:
let formatted = format!("{1} {0} {2}", "first", "second", "third");
// Output: "second first third"Format specifiers for controlling output:
// Number formatting
let pi = 3.1415926;
let formatted_float = format!("{:.2}", pi); // "3.14"
// Padding with zeros
let padded = format!("{:0>5}", "123"); // "00123"To reverse a string: .to_string().chars().rev().collect::<String>()
Try it yourself
use std::io;
fn main() {
let mut input_name = String::new();
let mut input_year = String::new();
io::stdin().read_line(&mut input_name).unwrap();
io::stdin().read_line(&mut input_year).unwrap();
let name = input_name.trim();
let year: i32 = input_year.trim().parse().unwrap();
// Write your code below
let secret_code =
println!("{}", secret_code);
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 33Variables Part 2
Type DeclarationNaming ConventionsType InferenceRecap - Initialize VariablesType Casting9Loops
For Over SeriesWhile LoopBreakContinueNested LoopLoop LabelsInfinite LoopRecap - Dynamic Input