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

How to do it...

  1. Create a Rust project to work on during this chapter with cargo new chapter-one
  2. Navigate to the newly created chapter-one folder. For the rest of this chapter, we will assume that your command line is currently in this directory
  3. Inside the src folder, create a new folder called bin
  4. Delete the generated lib.rs file, as we are not creating a library
  5. In the src/bin folder, create a file called concat.rs
  6. Add the following code and run it with cargo run --bin concat:
1  fn main() {
2 by_moving();
3 by_cloning();
4 by_mutating();
5 }
6
7 fn by_moving() {
8 let hello = "hello ".to_string();
9 let world = "world!";
10
11 // Moving hello into a new variable
12 let hello_world = hello + world;
13 // Hello CANNOT be used anymore
14 println!("{}", hello_world); // Prints "hello world!"
15 }
16
17 fn by_cloning() {
18 let hello = "hello ".to_string();
19 let world = "world!";
20
21 // Creating a copy of hello and moving it into a new variable
22 let hello_world = hello.clone() + world;
23 // Hello can still be used
24 println!("{}", hello_world); // Prints "hello world!"
25 }
26
27 fn by_mutating() {
28 let mut hello = "hello ".to_string();
29 let world = "world!";
30
31 // hello gets modified in place
32 hello.push_str(world);
33 // hello is both usable and modifiable
34 println!("{}", hello); // Prints "hello world!"
35 }
主站蜘蛛池模板: 正阳县| 贵德县| 成都市| 邳州市| 盘锦市| 宝坻区| 綦江县| 贡觉县| 万山特区| 都江堰市| 江津市| 宁阳县| 保定市| 泸西县| 永新县| 柞水县| 红河县| 辽源市| 新龙县| 西平县| 东乡族自治县| 乐亭县| 德格县| 清原| 福州市| 赤壁市| 察隅县| 太原市| 宝应县| 米易县| 米脂县| 墨竹工卡县| 阿克陶县| 沧源| 罗定市| 安远县| 西峡县| 珠海市| 大丰市| 阳泉市| 美姑县|