]> git.proxmox.com Git - rustc.git/blob - src/doc/rust-by-example/src/hello/print.md
New upstream version 1.62.1+dfsg1
[rustc.git] / src / doc / rust-by-example / src / hello / print.md
1 # Formatted print
2
3 Printing is handled by a series of [`macros`][macros] defined in [`std::fmt`][fmt]
4 some of which include:
5
6 * `format!`: write formatted text to [`String`][string]
7 * `print!`: same as `format!` but the text is printed to the console (io::stdout).
8 * `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.
11
12 All parse text in the same fashion. As a plus, Rust checks formatting
13 correctness at compile time.
14
15 ```rust,editable,ignore,mdbook-runnable
16 fn main() {
17 // In general, the `{}` will be automatically replaced with any
18 // arguments. These will be stringified.
19 println!("{} days", 31);
20
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
24 println!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob");
25
26 // As can named arguments.
27 println!("{subject} {verb} {object}",
28 object="the lazy dog",
29 subject="the quick brown fox",
30 verb="jumps over");
31
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);
39
40 // You can right-align text with a specified width. This will output
41 // " 1". 5 white spaces and a "1".
42 println!("{number:>5}", number=1);
43
44 // You can pad numbers with extra zeroes. This will output "000001".
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
50
51 // Rust even checks to make sure the correct number of arguments are
52 // used.
53 println!("My name is {0}, {1} {0}", "Bond");
54 // FIXME ^ Add the missing argument: "James"
55
56 // Only types that implement fmt::Display can be formatted with `{}`. User-
57 // defined types to not implement fmt::Display by default
58
59 #[allow(dead_code)]
60 struct Structure(i32);
61
62 // This will not compile because `Structure` does not implement
63 // fmt::Display
64 println!("This struct `{}` won't print...", Structure(3));
65 // FIXME ^ Comment out this line.
66
67 // For Rust 1.58 and above, you can directly capture the argument from
68 // surrounding variable. Just like the above, this will output
69 // " 1". 5 white spaces and a "1".
70 let number: f64 = 1.0;
71 let width: usize = 6;
72 println!("{number:>width$}");
73 }
74 ```
75
76 [`std::fmt`][fmt] contains many [`traits`][traits] which govern the display
77 of text. The base form of two important ones are listed below:
78
79 * `fmt::Debug`: Uses the `{:?}` marker. Format text for debugging purposes.
80 * `fmt::Display`: Uses the `{}` marker. Format text in a more elegant, user
81 friendly fashion.
82
83 Here, we used `fmt::Display` because the std library provides implementations
84 for these types. To print text for custom types, more steps are required.
85
86 Implementing the `fmt::Display` trait automatically implements the
87 [`ToString`] trait which allows us to [convert] the type to [`String`][string].
88
89 ### Activities
90
91 * Fix the two issues in the above code (see FIXME) so that it runs without
92 error.
93 * Add a `println!` macro call that prints: `Pi is roughly 3.142` by controlling
94 the number of decimal places shown. For the purposes of this exercise,
95 use `let pi = 3.141592` as an estimate for pi. (Hint: you may need to
96 check the [`std::fmt`][fmt] documentation for setting the number of
97 decimals to display)
98
99 ### See also:
100
101 [`std::fmt`][fmt], [`macros`][macros], [`struct`][structs],
102 and [`traits`][traits]
103
104 [fmt]: https://doc.rust-lang.org/std/fmt/
105 [macros]: ../macros.md
106 [string]: ../std/str.md
107 [structs]: ../custom_types/structs.md
108 [traits]: https://doc.rust-lang.org/std/fmt/#formatting-traits
109 [`ToString`]: https://doc.rust-lang.org/std/string/trait.ToString.html
110 [convert]: ../conversion/string.md