Formatted print
Printing is handled by a series of macros
defined in std::fmt
some of which include:
format!
: write formatted text toString
print!
: same asformat!
but the text is printed to the console (io::stdout).println!
: same asprint!
but a newline is appended.eprint!
: same asformat!
but the text is printed to the standard error (io::stderr).eprintln!
: same aseprint!
but a newline is appended.
All parse text in the same fashion. As a plus, Rust checks formatting correctness at compile time.
std::fmt
contains many traits
which govern the display
of text. The base form of two important ones are listed below:
fmt::Debug
: Uses the{:?}
marker. Format text for debugging purposes.fmt::Display
: Uses the{}
marker. Format text in a more elegant, user friendly fashion.
Here, we used fmt::Display
because the std library provides implementations
for these types. To print text for custom types, more steps are required.
Implementing the fmt::Display
trait automatically implements the
ToString
trait which allows us to convert the type to String
.
Activities
- Fix the two issues in the above code (see FIXME) so that it runs without error.
- Add a
println!
macro that prints:Pi is roughly 3.142
by controlling the number of decimal places shown. For the purposes of this exercise, uselet pi = 3.141592
as an estimate for pi. (Hint: you may need to check thestd::fmt
documentation for setting the number of decimals to display)