Rust 字符串拼接

Rust 有两类字符串,`String` 类型基于向量列表 `Vec<u8>`,另一类字符串是 `&str` 它是切片类型 `&[u8]`。

C++ 程序拼接字符串:

string s1 = "Hello,";
const string s2 = "world";
s1 += s2;

Rust 程序拼接字符串:

let mut s1 = "Hello,".to_string();
let s2 = "world".to_string();
s1 += &s2;

Rust 字符串的拼接,根本就是把加法操作符右侧的字符串,拷贝一份,并附到左侧字符串之后,同时右侧的字符串的所有权不受影响。Rust 语言的设计需要将「借用」显式写出,所以就比 C++ 多了一个借用操作符。

两个 `&str` 也不能直接相加,但可以将 `&str` 加到 String 上,并且,两个 String 相加,要将 + 右侧的转换为借用形式:

let s = "Hello," + "world"; // Can't use + with two &str
let s = s1 + &s2; // Move s1 to s, and concats s2 to s

对于 + 右侧的 String 它必需转换成 `&str` 才能被连接到另一个字符串上,因为字符串对象没有 Copy 特性。

更好的方式是使用 format! 宏:

let s1 = String::from("Hello"); let s2 = String::from("world."); let s = format!("{}, {}", s1, s2);

集合(Collection)是数据结构中最普遍的数据存放形式,Rust 标准库中提供了丰富的集合类型帮助开发者处理数据结构的操作。1. 向量:向量(Vector)是一个存放多值的单数据结构,该结构将相同类型的值线性的存放在内存中。2. 字符串。3 映射表:映射表(Map)在其他语言中广泛存在。其中应用最普遍的就是键值散列映射表(Hash Map)。