This recipe focuses on how to manipulate the print macros to perform various control operations in the data.
- Enter the following code in a Rust script named
decimal.rs
and compile them:
fn main(){ // Prints the first 2 numbers after the decimal points println!("{:.2}",1.2345 ); println!("================"); // print the binary hex and octal format println!("B: {:b} H: {:x} O: {:o}",10,10,10 ); println!("================"); // Shifts println!("{ten:>ws$}",ten=10, ws=5 ); println!("{ten:>0ws$}",ten=10, ws=5 ); }
2. The output of the code is as follows:
In the first print statement, we controlled the number of decimal points to be displayed in the Terminal. In the preceding code snippet, we set the value to be two after the colon symbol (:
) in the print statement, which tells the compiler to only print the first two decimal points of the variable in the runtime.
The next print statement displayed Rust's built-in feature that can convert the value to be printed in a different number format. We printed the binary, hex, and octal value of the decimal value 10. To perform this activity, we specifically mentioned the parameter after the colon symbol in the print statement. This is understood by the Rust compiler. At runtime, Rust would automatically convert the decimal type into the mentioned number format, where b
stands for binary, x
for hex, and o
for octal. This has to be given after :
in the print statement.
Next, the print
statement named arguments and we defined the white space (ws) type we wanted to. We have two arguments here: ten
and ws
. We had control over how we wanted to print the data and what kind of values we wanted to fill ws
with. In the first print statement, we filled it with blank spaces. In the second print statement, we explicitly mentioned zero, which is what we want to fill the gaps with. We declared the named argument inside the curly braces of the print statement and assigned its data value.