Math and Formatting
Programs run from top to bottom, one line at a time. Let's learn how to do math and build text in Rust!
Doing Math
Rust can do math with these operators:
Integer vs Float Division
In Rust, dividing two integers gives an integer (the decimal part is dropped). Use floats to get a decimal result:
If you want a decimal answer, make sure your numbers have .0 at the end!
Math with Variables
You can store numbers in variables and compute results:
Output:
15
Building Strings with format!()
The format!() macro lets you build strings by plugging in values:
Output:
Hello, Alex! You are 10 years old.
Use {} as a placeholder and pass the values after the format string.
Printing Directly with println!()
You can also put values right into println!() without using format!() first:
Output:
I have 7 blue balloons!
Order of Operations
Rust follows math rules — multiplication and division happen before addition and subtraction:
Use parentheses () when you want to change the order!