1
1
# Formatted print
2
2
3
- Printing is handled by a series of [ ` macros ` ] [ macros ] defined in [ ` std::fmt ` ] [ fmt ]
4
- some of which include:
3
+ Printing is handled by a series of [ ` macros ` ] [ macros ] defined in
4
+ [ ` std::fmt ` ] [ fmt ] some of which include:
5
5
6
6
* ` format! ` : write formatted text to [ ` String ` ] [ string ]
7
- * ` print! ` : same as ` format! ` but the text is printed to the console (io::stdout).
7
+ * ` print! ` : same as ` format! ` but the text is printed to the console
8
+ (io::stdout).
8
9
* ` println! ` : same as ` print! ` but a newline is appended.
9
- * ` eprint! ` : same as ` format! ` but the text is printed to the standard error (io::stderr).
10
- * ` eprintln! ` : same as ` eprint! ` but a newline is appended.
10
+ * ` eprint! ` : same as ` print! ` but the text is printed to the standard error
11
+ (io::stderr).
12
+ * ` eprintln! ` : same as ` eprint! ` but a newline is appended.
11
13
12
14
All parse text in the same fashion. As a plus, Rust checks formatting
13
15
correctness at compile time.
@@ -18,11 +20,9 @@ fn main() {
18
20
// arguments. These will be stringified.
19
21
println!("{} days", 31);
20
22
21
- // Without a suffix, 31 becomes an i32. You can change what type 31 is
22
- // by providing a suffix. The number 31i64 for example has the type i64.
23
-
24
- // There are various optional patterns this works with. Positional
25
- // arguments can be used.
23
+ // Positional arguments can be used. Specifying an integer inside `{}`
24
+ // determines which additional argument will be replaced. Arguments start
25
+ // at 0 immediately after the format string.
26
26
println!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob");
27
27
28
28
// As can named arguments.
@@ -31,29 +31,46 @@ fn main() {
31
31
subject="the quick brown fox",
32
32
verb="jumps over");
33
33
34
- // Special formatting can be specified after a `:`.
35
- println!("{} of {:b} people know binary, the other half doesn't", 1, 2);
34
+ // Different formatting can be invoked by specifying the format character
35
+ // after a `:`.
36
+ println!("Base 10: {}", 69420); // 69420
37
+ println!("Base 2 (binary): {:b}", 69420); // 10000111100101100
38
+ println!("Base 8 (octal): {:o}", 69420); // 207454
39
+ println!("Base 16 (hexadecimal): {:x}", 69420); // 10f2c
40
+
41
+ // You can right-justify text with a specified width. This will
42
+ // output " 1". (Four white spaces and a "1", for a total width of 5.)
43
+ println!("{number:>5}", number=1);
36
44
37
- // You can right-align text with a specified width. This will output
38
- // " 1". 5 white spaces and a "1".
39
- println!("{number:>width$}", number=1, width=6);
45
+ // You can pad numbers with extra zeroes,
46
+ println!("{number:0>5}", number=1); // 00001
47
+ // and left-adjust by flipping the sign. This will output "10000".
48
+ println!("{number:0<5}", number=1); // 10000
40
49
41
- // You can pad numbers with extra zeroes. This will output "000001" .
42
- println!("{number:0>width$}", number=1, width=6 );
50
+ // You can use named arguments in the format specifier by appending a `$` .
51
+ println!("{number:0>width$}", number=1, width=5 );
43
52
44
- // Rust even checks to make sure the correct number of arguments are
45
- // used.
53
+ // Rust even checks to make sure the correct number of arguments are used.
46
54
println!("My name is {0}, {1} {0}", "Bond");
47
55
// FIXME ^ Add the missing argument: "James"
48
56
49
- // Create a structure named `Structure` which contains an `i32`.
50
- #[allow(dead_code)]
57
+ // Only types that implement fmt::Display can be formatted with `{}`. User-
58
+ // defined types do not implement fmt::Display by default.
59
+
60
+ #[allow(dead_code)] // disable `dead_code` which warn against unused module
51
61
struct Structure(i32);
52
62
53
- // However, custom types such as this structure require more complicated
54
- // handling. This will not work.
55
- println!("This struct `{}` won't print...", Structure(3));
56
- // FIXME ^ Comment out this line.
63
+ // This will not compile because `Structure` does not implement
64
+ // fmt::Display.
65
+ // println!("This struct `{}` won't print...", Structure(3));
66
+ // TODO ^ Try uncommenting this line
67
+
68
+ // For Rust 1.58 and above, you can directly capture the argument from a
69
+ // surrounding variable. Just like the above, this will output
70
+ // " 1", 4 white spaces and a "1".
71
+ let number: f64 = 1.0;
72
+ let width: usize = 5;
73
+ println!("{number:>width$}");
57
74
}
58
75
```
59
76
@@ -62,28 +79,30 @@ of text. The base form of two important ones are listed below:
62
79
63
80
* ` fmt::Debug ` : Uses the ` {:?} ` marker. Format text for debugging purposes.
64
81
* ` fmt::Display ` : Uses the ` {} ` marker. Format text in a more elegant, user
65
- friendly fashion.
82
+ friendly fashion.
66
83
67
84
Here, we used ` fmt::Display ` because the std library provides implementations
68
85
for these types. To print text for custom types, more steps are required.
69
86
70
87
Implementing the ` fmt::Display ` trait automatically implements the
71
88
[ ` ToString ` ] trait which allows us to [ convert] the type to [ ` String ` ] [ string ] .
72
89
90
+ In * line 43* , ` #[allow(dead_code)] ` is an [ attribute] which only applies to the module after it.
91
+
73
92
### Activities
74
93
75
- * Fix the two issues in the above code (see FIXME) so that it runs without
76
- error.
77
- * Add a ` println! ` macro that prints: ` Pi is roughly 3.142 ` by controlling
78
- the number of decimal places shown. For the purposes of this exercise,
79
- use ` let pi = 3.141592 ` as an estimate for pi. (Hint: you may need to
80
- check the [ ` std::fmt ` ] [ fmt ] documentation for setting the number of
81
- decimals to display)
94
+ * Fix the issue in the above code (see FIXME) so that it runs without
95
+ error.
96
+ * Try uncommenting the line that attempts to format the ` Structure ` struct
97
+ (see TODO)
98
+ * Add a ` println! ` macro call that prints: ` Pi is roughly 3.142 ` by controlling
99
+ the number of decimal places shown. For the purposes of this exercise, use
100
+ ` let pi = 3.141592 ` as an estimate for pi. (Hint: you may need to check the
101
+ [ ` std::fmt ` ] [ fmt ] documentation for setting the number of decimals to display)
82
102
83
103
### See also:
84
104
85
- [ ` std::fmt ` ] [ fmt ] , [ ` macros ` ] [ macros ] , [ ` struct ` ] [ structs ] ,
86
- and [ ` traits ` ] [ traits ]
105
+ [ ` std::fmt ` ] [ fmt ] , [ ` macros ` ] [ macros ] , [ ` struct ` ] [ structs ] , [ ` traits ` ] [ traits ] , and [ ` dead_code ` ] [ dead_code ]
87
106
88
107
[ fmt ] : https://doc.rust-lang.org/std/fmt/
89
108
[ macros ] : ../macros.md
@@ -92,3 +111,5 @@ and [`traits`][traits]
92
111
[ traits ] : https://doc.rust-lang.org/std/fmt/#formatting-traits
93
112
[ `ToString` ] : https://doc.rust-lang.org/std/string/trait.ToString.html
94
113
[ convert ] : ../conversion/string.md
114
+ [ attribute ] : ../attribute.md
115
+ [ dead_code ] : ../attribute/unused.md
0 commit comments