Skip to content

Commit

Permalink
Update 瞎记一下.md
Browse files Browse the repository at this point in the history
  • Loading branch information
shaoting0730 committed Jul 8, 2024
1 parent 940c020 commit 90f2f10
Showing 1 changed file with 21 additions and 1 deletion.
22 changes: 21 additions & 1 deletion 知识截图/瞎记一下.md
Original file line number Diff line number Diff line change
Expand Up @@ -292,13 +292,33 @@ let mut s = String::from("foo");
s.push_str("bar"); // 可以增加多个字符
s.push("w") // 可以增加一个字符
```
使用 + 运算符或 format! 宏拼接字符串
`push_str` 方法采用字符串 slice,因为我们并不需要获取参数的所有权。
```
let mut s1 = String::from("foo");
let s2 = "bar";
s1.push_str(s2);
println!("s2 is {}", s2); // s1 s2均仍可用
```
使用 `+` 运算符或 `format!` 宏拼接字符串
```
let s1 = String::from("Hello, ");
let s2 = String::from("world!");
let s3 = s1 + &s2; // 注意 s1 被移动了,不能继续使用
这个语句会获取 s1 的所有权,附加上从 s2 中拷贝的内容,并返回结果的所有权
```
`format!``println!` 的工作原理相同,不过不同于将输出打印到屏幕上,它返回一个带有结果内容的 `String`:
```
let s1 = String::from("tic");
let s2 = String::from("tac");
let s3 = String::from("toe");
let s = format!("{}-{}-{}", s1, s2, s3);
```
** Rust 不允许使用索引获取 String 字符 **






Expand Down

0 comments on commit 90f2f10

Please sign in to comment.