上QQ阅读APP看书,第一时间看更新
How to do it...
- In the src/bin folder, create a file called format.rs
- 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 }