Formatted output
1. fn main() {
2. // In general, the `{}` will be automatically replaced with any
3. // arguments. These will be stringified.
4. println!("{} days", 31);
6. // Without a suffix, 31 becomes an i32. You can change what type 31 is
7. // by providing a suffix. The number 31i64 for example has the type i64.
9. // There are various optional patterns this works with. Positional
10. // arguments can be used.
11. println!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob");
13. // As can named arguments.
14. println!("{subject} {verb} {object}",
15. object="the lazy dog",
16. subject="the quick brown fox",
17. verb="jumps over");
19. // Special formatting can be specified after a `:`.
20. println!("{} of {:b} people know binary, the other half doesn't", 1, 2);
22. // You can right-align text with a specified width. This will output
23. // " 1". 5 white spaces and a "1".
24. println!("{number:>width$}", number=1, width=6);
26. // You can pad numbers with extra zeroes. This will output "000001".
27. println!("{number:0>width$}", number=1, width=6);
29. // Rust even checks to make sure the correct number of arguments are
30. // used.
31. println!("My name is {0}, {1} {0}", "Bond");
32. // FIXME ^ Add the missing argument: "James"
34. // Create a structure named `Structure` which contains an `i32`.
35. #[allow(dead_code)]
36. struct Structure(i32);
38. // However, custom types such as this structure require more complicated
39. // handling. This will not work.
40. println!("This struct `{}` won't print...", Structure(3));
41. // FIXME ^ Comment out this line.
43. // For Rust 1.58 and above, you can directly capture the argument from
44. // surrounding variable. Just like the above, this will output
45. // " 1". 5 white spaces and a "1".
46. let number: f64 = 1.0;
47. let width: usize = 6;
48. println!("{number:>width$}");
49. }
[std::fmt][fmt] contains many [traits][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][string].
