官术网_书友最值得收藏!

How to do it...

  1. In the src/bin folder, create a file called format.rs
  2. Add the following code and run it with cargo run --bin format
1  fn main() {
2 let colour = "red";
3 // The '{}' it the formatted string gets replaced by the
parameter
4 let favourite = format!("My favourite colour is {}", colour);
5 println!("{}", favourite);
6
7 // You can add multiple parameters, which will be
8 // put in place one after another
9 let hello = "hello ";
10 let world = "world!";
11 let hello_world = format!("{}{}", hello, world);
12 println!("{}", hello_world); // Prints "hello world!"
13
14 // format! can concatenate any data types that
15 // implement the 'Display' trait, such as numbers
16 let favourite_num = format!("My favourite number is {}", 42);
17 println!("{}", favourite_num); // Prints "My favourite number
is 42"
18
19 // If you want to include certain parameters multiple times
20 // into the string, you can use positional parameters
21 let duck_duck_goose = format!("{0}, {0}, {0}, {1}!", "duck",
"goose");
22 println!("{}", duck_duck_goose); // Prints "duck, duck, duck,
goose!"
23
24 // You can even name your parameters!
25 let introduction = format!(
26 "My name is {surname}, {forename} {surname}",
27 surname="Bond",
28 forename="James"
29 );
30 println!("{}", introduction) // Prints "My name is Bond, James
Bond"
31 }
主站蜘蛛池模板: 福州市| 抚州市| 萍乡市| 铜梁县| 贵德县| 莱阳市| 弥渡县| 许昌县| 定远县| 金门县| 巴马| 卢氏县| 基隆市| 恩施市| 峨山| 武宁县| 南郑县| 海伦市| 大城县| 罗甸县| 胶南市| 安陆市| 革吉县| 外汇| 大埔县| 甘谷县| 河西区| 襄汾县| 彭泽县| 金湖县| 松原市| 喀喇沁旗| 武穴市| 乃东县| 陇川县| 慈利县| 灵川县| 武城县| 三门县| 成武县| 抚远县|