Previously, we've learned about data types, specifically strings (like "Hello"
) and integers (like 42
).
Engagement Message
Let's see if you remember which type the value 2077
belongs to?
In Rust, you'll often need to display information that combines text and numbers. You've already seen how the println!
macro handles this seamlessly using placeholders ({}
).
For example: println!("Score: {}", 95)
The macro automatically handles converting the number into text for display. This is a convenient feature for quick outputs.
Engagement Message
What do you think the code above would display when it runs?
But what if you wanted to store the combined text in a variable instead of just printing it? You can't directly combine a string and an integer like "Score: " + 95
in Rust.
Rust catches these type mismatches before your program even runs.
Engagement Message
Why do you think this check might be helpful?
To solve this, Rust gives us the format!
macro. It works exactly like println!
, but instead of printing the message to the screen, it the final string and lets you save it in a variable to use later.
