Skip to content

Commit c95f29e

Browse files
print.md synchronizes official documents (#190)
* print.md synchronizes official documents * Modified format without translation * Update print.md * Update src/hello/print.md --------- Co-authored-by: YangFong <yangfong2022@gmail.com>
1 parent e0846cb commit c95f29e

File tree

2 files changed

+99
-56
lines changed

2 files changed

+99
-56
lines changed

english/src/hello/print.md

+56-35
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
# Formatted print
22

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:
55

66
* `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).
89
* `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.
1113

1214
All parse text in the same fashion. As a plus, Rust checks formatting
1315
correctness at compile time.
@@ -18,11 +20,9 @@ fn main() {
1820
// arguments. These will be stringified.
1921
println!("{} days", 31);
2022
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.
2626
println!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob");
2727
2828
// As can named arguments.
@@ -31,29 +31,46 @@ fn main() {
3131
subject="the quick brown fox",
3232
verb="jumps over");
3333
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);
3644
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
4049
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);
4352
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.
4654
println!("My name is {0}, {1} {0}", "Bond");
4755
// FIXME ^ Add the missing argument: "James"
4856
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
5161
struct Structure(i32);
5262
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$}");
5774
}
5875
```
5976

@@ -62,28 +79,30 @@ of text. The base form of two important ones are listed below:
6279

6380
* `fmt::Debug`: Uses the `{:?}` marker. Format text for debugging purposes.
6481
* `fmt::Display`: Uses the `{}` marker. Format text in a more elegant, user
65-
friendly fashion.
82+
friendly fashion.
6683

6784
Here, we used `fmt::Display` because the std library provides implementations
6885
for these types. To print text for custom types, more steps are required.
6986

7087
Implementing the `fmt::Display` trait automatically implements the
7188
[`ToString`] trait which allows us to [convert] the type to [`String`][string].
7289

90+
In *line 43*, `#[allow(dead_code)]` is an [attribute] which only applies to the module after it.
91+
7392
### Activities
7493

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)
82102

83103
### See also:
84104

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]
87106

88107
[fmt]: https://doc.rust-lang.org/std/fmt/
89108
[macros]: ../macros.md
@@ -92,3 +111,5 @@ and [`traits`][traits]
92111
[traits]: https://doc.rust-lang.org/std/fmt/#formatting-traits
93112
[`ToString`]: https://doc.rust-lang.org/std/string/trait.ToString.html
94113
[convert]: ../conversion/string.md
114+
[attribute]: ../attribute.md
115+
[dead_code]: ../attribute/unused.md

src/hello/print.md

+43-21
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,9 @@ fn main() {
1616
// 变量内容会转化成字符串。
1717
println!("{} days", 31);
1818
19-
// 不加后缀的话,31 就自动成为 i32 类型。
20-
// 你可以添加后缀来改变 31 的类型(例如使用 31i64 声明 31 为 i64 类型)。
21-
22-
// 用变量替换字符串有多种写法。
23-
// 比如可以使用位置参数。
19+
// 可以使用位置参数。
20+
// 在 `{}` 中指定一个整数确定将替换哪个附加参数。
21+
// 参数从紧接在格式字符串之后的 0 开始。
2422
println!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob");
2523
2624
// 可以使用命名参数。
@@ -29,49 +27,73 @@ fn main() {
2927
subject="the quick brown fox",
3028
verb="jumps over");
3129
32-
// 可以在 `:` 后面指定特殊的格式。
33-
println!("{} of {:b} people know binary, the other half don't", 1, 2);
30+
// 通过在 `:` 后面指定格式字符,可以调用不同的格式。
31+
println!("Base 10: {}", 69420); // 69420
32+
println!("Base 2 (binary): {:b}", 69420); // 10000111100101100
33+
println!("Base 8 (octal): {:o}", 69420); // 207454
34+
println!("Base 16 (hexadecimal): {:x}", 69420); // 10f2c
35+
36+
// 可以用指定的宽度对文本进行右对齐。
37+
// 这将输出“ 1”。(四个空格和一个“1”,总宽度为5)
38+
println!("{number:>5}", number=1);
3439
35-
// 你可以按指定宽度来右对齐文本。
36-
// 下面语句输出 " 1",5 个空格后面连着 1。
37-
println!("{number:>width$}", number=1, width=6);
40+
// 你可以在数字左边补 0,
41+
println!("{number:0>5}", number=1); // 00001
42+
// 在数字右边补零,下面语句输出 "000001"。
43+
println!("{number:0<5}", number=1); // 10000
3844
39-
// 你可以在数字左边补 0。下面语句输出 "000001"
40-
println!("{number:>0width$}", number=1, width=6);
45+
// 可以通过添加 `$` 在格式说明符中使用命名参数
46+
println!("{number:0>width$}", number=1, width=5);
4147
4248
// println! 会检查使用到的参数数量是否正确。
4349
println!("My name is {0}, {1} {0}", "Bond");
44-
// 改正 ^ 补上漏掉的参数:"James"
50+
// FIXME ^ 补上漏掉的参数:"James"
4551
46-
// 创建一个包含单个 `i32` 的结构体(structure)。命名为 `Structure`。
47-
#[allow(dead_code)]
52+
// 只有实现了fmt::Display的类型才能使用'{}'进行格式化。
53+
// 默认情况下,用户定义的类型不实现fmt::Display。
54+
#[allow(dead_code)] // 禁用对未使用模块发出警告的' dead_code '
4855
struct Structure(i32);
4956
50-
// 但是像结构体这样的自定义类型需要更复杂的方式来处理。
57+
// 这将不会编译,因为 `Structure` 没有实现
5158
// 下面语句无法运行。
52-
println!("This struct `{}` won't print...", Structure(3));
53-
// 改正 ^ 注释掉此行。
59+
// println!("This struct `{}` won't print...", Structure(3));
60+
// TODO ^ 注释掉此行。
61+
62+
// 对于 Rust 1.58 及更高版本,你可以直接从周围变量捕获参数。
63+
// 就像上面一样,这将输出“ 1”,4 个空格和 1 个“1”。
64+
let number: f64 = 1.0;
65+
let width: usize = 5;
66+
println!("{number:>width$}");
5467
}
5568
```
5669

57-
[`std::fmt`][fmt] 包含多种 [`trait`][traits](特质)来控制文字显示,其中重要的两种 trait 的基本形式如下:
70+
[`std::fmt`][fmt] 包含多种 [`traits`][traits](特质)来控制文字显示,其中重要的两种 trait 的基本形式如下:
5871

5972
- `fmt::Debug`:使用 `{:?}` 标记。格式化文本以供调试使用。
6073
- `fmt::Display`:使用 `{}` 标记。以更优雅和友好的风格来格式化文本。
6174

6275
上例使用了 `fmt::Display`,因为标准库提供了那些类型的实现。若要打印自定义类型的文本,需要更多的步骤。
6376

77+
实现 `fmt::Display` 特性会自动实现 [`ToString`] 特征,它允许我们将类型 [convert][`String`][string]
78+
79+
*第 43 行*中,`#[allow(dead_code)]` 是一个 [attribute],只适用于它后面的模块。
80+
6481
### 动手试一试
6582

66-
- 改正上面代码中的两个错误(见 “改正”),使它可以没有错误地运行。
83+
- 改正上面代码中的错误(见 FIXME),使它可以没有错误地运行。
84+
- 尝试取消注释,输出结构体内容(见 TODO)。
6785
- 再用一个 `println!` 宏,通过控制显示的小数位数来打印:`Pi is roughly 3.142`(Pi 约等于 3.142)。为了达到练习目的,使用 `let pi = 3.141592` 作为 Pi 的近似值(提示:设置小数位的显示格式可以参考文档 [`std::fmt`][fmt])。
6886

6987
### 参见:
7088

71-
[`std::fmt`][fmt], [`macros`][macros], [`struct`][structs] [`trait`][traits]
89+
[`std::fmt`][fmt], [`macros`][macros], [`struct`][structs], [`traits`][traits] [`dead_code`][dead_code]
7290

7391
[fmt]: https://rustwiki.org/zh-CN/std/fmt/
7492
[macros]: ../macros.md
7593
[string]: ../std/str.md
7694
[structs]: ../custom_types/structs.md
7795
[traits]: ../trait.md
96+
[`ToString`]: https://doc.rust-lang.org/std/string/trait.ToString.html
97+
[convert]: ../conversion/string.md
98+
[attribute]: ../attribute.md
99+
[dead_code]: ../attribute/unused.md

0 commit comments

Comments
 (0)