定义
str
Rust
的核心中只有一种字符串类型:str
,它经常以借用的形式出现:&str
(字符串slice
),并且被存储在二进制文件中
String
String
由标准库提供,它可增长、可变、有所有权
这两种类型都是UTF-8
编码的
在Rust
标准库中,有很多&str
和String
的变体,通常以它们为后缀作为区分,分别代表可借用的和有所有权的类型
新建、修改
新建
let mut s = String::**new**();
let mut s2 = String::**from**("hello");
let mut s3 = "hello".**to_string**();
修改
使用push_str()
let mut s1 = String::from("foo");
let s2 = "bar";
s1.push_str(s2); println!("s2 is {}", s2);
使用push()
附加单个字符
let mut s = String::from("lo");
s.push('l');
拼接
使用 **+**
拼接
+
操作符会为第一个参数调用add
方法,根据参数签名:fn add(self, s: &str) -> String {
这会获取第一个参数的所有权,但是只需要第二个参数的引用
let s1 = String::from("Hello, ");
let s2 = String::from("world!");
let s3 = s1 + &s2; // 注意 s1 被移动了,不能继续使用
使用**format!**
拼接
let s1 = String::from("tic");
let s2 = String::from("tac");
let s3 = String::from("toe");
let s = format!("{}-{}-{}", s1, s2, s3);
String的存储
String
内部使用 Vec<u8>
存储,即将字符串的Unicode
转换为字节后存储在Vector
中
可以使用字符串slice
来获取字符,但是需要自己计算清楚字符的字节范围,否则可能报错
可以使用chars()
方法获取字符串的迭代器,逐个取字符
for c in "你好".chars() {
println!("{}", c);
}