The print macros are used to print on console, either on standard
output (a.k.a.: stdout) or standard error (a.k.a.: stderr). The ones
terminating with the suffix ln add a line feed character at the end
of the printed string. See Table 1 for a sum-up of
those macros.
Table 1:Print macros
Macro | Stream | Line feed |
|---|---|---|
|
| No |
|
| Yes |
|
| No |
|
| Yes |
All macros take a literal string as first argument, then zero or more
values that are used to replace format string markers {}.
9.1.1Printing of simple objects¶
Printing a simple string:
println!("Hello, world!");Hello, world!
Using unnamed markers:
println!("my values: {} {}", 12.34, 789);my values: 12.34 789
Using named markers:
println!("my_values: {a} - {b}", b=12.34, a=789);my_values: 789 - 12.34
Printing a variable:
let my_var = 123;
println!("my_var: {my_var}");my_var: 123
Insert leading characters:
let my_var = 123;
println!("my_var: {my_var:05}");my_var: 00123
Setting precision on a float:
println!("x: {:.5}", 0.123456789);x: 0.12346
Using a variable for precision:
let prec = 3;
println!("x: {:.*}", prec, 0.123456789);mismatched types9.1.2Printing of complex objects¶
Printing a complex object requires a special formatter. The easiest
way is to use the Debug formatter that is included in core objects
and objects from the standard library. For custom types, the Debug
trait can easily be implemented using the derive() attribute as we
will see later.
Let us define a tuple object with three values:
let t = (1.5, "abc", true);The Debug formatter being implemented for tuple objects, we can use
the special debug formatter operator ? to print our tuple:
println!("{t:?}");Using the # option, we can also enable the pretty-print output:
println!("{t:#?}");