Debug and Display
All types which want to be printable must implement the std::fmt
formatting trait: std::fmt::Debug
or std::fmt::Display
.
Automatic implementations are only provided for types such as in the std
library. All others have to be manually implemented.
Debug
The implementation of Debug
is very straightforward: All types can derive
the std::fmt::Debug
implementation. This is not true for std::fmt::Display
which must be manually implemented.
{:?}
must be used to print out the type which has implemented the Debug
trait.
- 🌟
- 🌟🌟 So
fmt::Debug
definitely makes one type printable, but sacrifices some elegance. Maybe we can get more elegant by replacing{:?}
with something else( but not{}
!)
- 🌟🌟 We can also manually implement
Debug
trait for our types
Display
Yeah, Debug
is simple and easy to use. But sometimes we want to customize the output appearance of our type. This is where Display
really shines.
Unlike Debug
, there is no way to derive the implementation of the Display
trait, we have to manually implement it.
Another thing to note: the placeholder for Display
is {}
not {:?}
.
- 🌟🌟
?
operator
Implementing fmt::Display
for a structure whose elements must be handled separately is tricky. The problem is each write!
generates a fmt::Result
which must be handled in the same place.
Fortunately, Rust provides the ?
operator to help us eliminate some unnecessary codes for dealing with fmt::Result
.
- 🌟🌟
You can find the solutions here(under the solutions path), but only use it when you need it :)