Skip to content

Commit 7129ee4

Browse files
authored
Merge pull request #1536 from pezcore/enhancement/print
Enhancement/print
2 parents dfe0c5c + 2c9f70d commit 7129ee4

File tree

1 file changed

+21
-12
lines changed

1 file changed

+21
-12
lines changed

src/hello/print.md

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,9 @@ fn main() {
1818
// arguments. These will be stringified.
1919
println!("{} days", 31);
2020
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
2624
println!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob");
2725
2826
// As can named arguments.
@@ -31,27 +29,38 @@ fn main() {
3129
subject="the quick brown fox",
3230
verb="jumps over");
3331
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);
3639
3740
// You can right-align text with a specified width. This will output
3841
// " 1". 5 white spaces and a "1".
39-
println!("{number:>width$}", number=1, width=6);
42+
println!("{number:>5}", number=1);
4043
4144
// 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+
4350
4451
// Rust even checks to make sure the correct number of arguments are
4552
// used.
4653
println!("My name is {0}, {1} {0}", "Bond");
4754
// FIXME ^ Add the missing argument: "James"
4855
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+
5059
#[allow(dead_code)]
5160
struct Structure(i32);
5261
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
5564
println!("This struct `{}` won't print...", Structure(3));
5665
// FIXME ^ Comment out this line.
5766

0 commit comments

Comments
 (0)