@@ -18,11 +18,9 @@ fn main() {
18
18
// arguments. These will be stringified.
19
19
println!("{} days", 31);
20
20
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.
21
+ // Positional arguments can be used. Specifying an integer inside `{}`
22
+ // determines which additional argument will be replaced. Arguments start
23
+ // at 0 immediately after the format string
26
24
println!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob");
27
25
28
26
// As can named arguments.
@@ -31,27 +29,38 @@ fn main() {
31
29
subject="the quick brown fox",
32
30
verb="jumps over");
33
31
34
- // Special formatting can be specified after a `:`.
35
- println!("{} of {:b} people know binary, the other half doesn't", 1, 2);
32
+ // Different formatting can invoked by specified format character after a
33
+ // `:`.
34
+ println!("Base 10 repr: {}", 69420);
35
+ println!("Base 2 (binary) repr: {:b}", 69420);
36
+ println!("Base 8 (octal) repr: {:o}", 69420);
37
+ println!("Base 16 (hexadecimal) repr: {:x}", 69420);
38
+ println!("Base 16 (hexadecimal) repr: {:X}", 69420);
36
39
37
40
// You can right-align text with a specified width. This will output
38
41
// " 1". 5 white spaces and a "1".
39
- println!("{number:>width$ }", number=1, width=6 );
42
+ println!("{number:>5 }", number=1);
40
43
41
44
// You can pad numbers with extra zeroes. This will output "000001".
42
- println!("{number:0>width$}", number=1, width=6);
45
+ println!("{number:0>5}", number=1);
46
+
47
+ // You can use named arguments in the format specifier by appending a `$`
48
+ println!("{number:0>width$}", number=1, width=5);
49
+
43
50
44
51
// Rust even checks to make sure the correct number of arguments are
45
52
// used.
46
53
println!("My name is {0}, {1} {0}", "Bond");
47
54
// FIXME ^ Add the missing argument: "James"
48
55
49
- // Create a structure named `Structure` which contains an `i32`.
56
+ // Only types that implement fmt::Display can be formatted with `{}`. User-
57
+ // defined types to not implement fmt::Display by default
58
+
50
59
#[allow(dead_code)]
51
60
struct Structure(i32);
52
61
53
- // However, custom types such as this structure require more complicated
54
- // handling. This will not work.
62
+ // This will not compile because `Structure` does not implement
63
+ // fmt::Display
55
64
println!("This struct `{}` won't print...", Structure(3));
56
65
// FIXME ^ Comment out this line.
57
66
0 commit comments