[Rust] String 与 &str 详解

String 与 &str 详解

字符串贯穿所有代码,但 Rust 的字符串和其他语言差别最大------UTF-8 编码 + 所有权规则叠加在一起,让它成了新手翻车重灾区。本章系统梳理两种字符串类型、全部常用方法和经典陷阱。

本节要解决什么问题

写过 Python/Java/Go 的人第一次用 Rust 字符串几乎都会困惑:

  • 为什么字符串类型有两个?String 和 &str 到底什么关系?
  • 为什么 "hello"[0] 编译不过?
  • 为什么 s.len() 对中文返回的不是"字数"?
  • 为什么 s1 + s2 会把 s1"用掉"?

这些问题背后是两个设计决策:Rust 字符串永远是 UTF-8 编码的 (不是字节数组,也不是 UTF-16),且所有权规则同样适用于字符串。理解了这两点,所有"怪异"行为都能推导出来。

1. String 与 &str 的本质

1.1 String:拥有所有权的堆缓冲区

String 本质是一个包装了 Vec<u8> 的结构体,缓冲区里存的是 UTF-8 字节:

yaml 复制代码
String {
    ptr:  ──────►  [ h | e | l | l | o ]   ← 堆上的缓冲区(UTF-8 字节)
    len:  5              (当前字节数)
    capacity: 10         (缓冲区容量)
}

String 拥有这块缓冲区:可以增长、缩小、修改;离开作用域时自动释放。

1.2 &str:字符串切片(借用视图)

&str 是一个胖指针:指向某段 UTF-8 字节 + 长度,本身不拥有数据:

python 复制代码
&str { ptr: 指向某处缓冲区, len: 字节数 }

数据可以在三个地方,&str 都能指向它们:

rust 复制代码
let a: &str = "hello";          // ① 指向程序二进制的只读段(字面量)
let s = String::from("hello");
let b: &str = &s;               // ② 指向某个 String 的堆缓冲区
let arr: [u8; 5] = *b"hello";
// ③ 指向栈上/静态区的字节(不常见,如 C 字符串转换场景)

关键结论: &str 是"借来的一段 UTF-8 文本",String 是"自己拥有的一段可变 UTF-8 文本" 。String 可以随时变成 &str(借用),&str 不能凭空变成 String(除非分配内存拷贝)。

1.3 三种写法的转换关系

rust 复制代码
let s = String::from("hello");
let t: &str = "world";

&s          // &String ------ String 的引用
s.as_str()  // &str
&s[..]      // &str(全区间切片)
&t          // &str 本身
t.to_string()   // String(分配 + 拷贝)
s.clone()       // String(分配 + 拷贝)
String::from(t) // String
t.into()        // String

编译器会在需要 &str 的地方自动把 &String 降级(deref 强转 ),所以传参时 &String 和 &str 都能编译通过------但函数签名应该写哪个?

2. 创建 String 的方式

rust 复制代码
let a = String::new();                    // 空
let b = String::from("hello");            // 从字面量
let c = "hello".to_string();              // 同上,Display 转换(blanket impl,见 07 章)
let d: String = "hello".into();           // From/Into
let e = format!("{}-{}", 1, "a");         // 拼接场景首选
let f = "ab".repeat(3);                   // "ababab"
let g = String::from_utf8(vec![104, 105]).unwrap(); // 从 UTF-8 字节构造
let mut h = String::with_capacity(1024);  // 预分配,避免反复扩容

性能提示:已知要攒一个大字符串时,String::with_capacity + push_str 比 + 反复拼接快得多(后者每次都可能重新分配)。

3. String 常用方法

3.1 添加内容

rust 复制代码
let mut s = String::from("he");

s.push('l');            // 追加一个 char:hel
s.push_str("lo");       // 追加一段 &str:hello
s.extend("!!".chars()); // 追加迭代器内容:hello!!
s.insert(0, 'H');       // 在字节索引 0 处插入 char:Hello!!(索引见第 6 节陷阱)

3.2 + 运算符的陷阱

rust 复制代码
let s1 = String::from("hello, ");
let s2 = String::from("world");

let s3 = s1 + &s2;   // ⚠️ s1 被"吃掉"(move),s2 只是借用
// println!("{s1}"); // ❌ 编译错误:s1 已被 move

+ 的签名是 fn add(self, rhs: &str) -> String------左边按值拿走。所以:

  • 想保留 s1,不要用 +;
  • 拼接多个片段,用 format!(借用所有参数,还支持任意类型):
rust 复制代码
let full = format!("{s1}{s2}!");   // s1、s2 都还在

3.3 删除内容

rust 复制代码
let mut s = String::from("hello");

s.pop();                    // 弹出末尾 char,返回 Option<char> → "hell"
s.truncate(2);              // 截断到字节长度 2 → "he"(必须在字符边界上!)
s.clear();                  // 清空 → ""
s.remove(0);                // 移除字节索引处的 char(按字节索引!)
s.drain(1..3);              // 移除一段区间,返回迭代器
s.replace_range(1..3, "XY");// 替换一段区间

3.4 修改与转换

rust 复制代码
let s = String::from("  Hello World  ");

s.to_uppercase();     // 全大写
s.to_lowercase();     // 全小写
s.trim();             // 去两端空白 → "Hello World"
s.trim_start();       // 去左端
s.trim_end();         // 去右端
s.trim_matches(' ');  // 去两端指定字符
s.trim_start_matches("hi"); // 去左端指定前缀(重复出现全去掉)

s.replace("World", "Rust");      // 全部替换
s.replacen("l", "L", 2);         // 只替换前 2 处
s.replace_range(..5, "Hi");      // 区间替换

s.capacity();         // 当前容量
s.reserve(100);       // 预留 100 字节容量
s.shrink_to_fit();    // 收缩到恰好 len

注意 trim 类方法返回的是 &str(借用),不是新 String。

4. &str 常用方法

&str 的方法大都是"只读"的检查、查找、切分------这正是它作为视图的定位。

4.1 检查与查找

ruby 复制代码
let s = "hello.rs";

s.contains("lo");        // true ------ 是否包含子串
s.starts_with("hello");  // true ------ 前缀
s.ends_with(".rs");      // true ------ 后缀
s.find("lo");            // Some(3) ------ 子串起始字节索引(Option<usize>)
s.rfind(".");            // Some(7) ------ 从右往左找
s.eq_ignore_ascii_case("HELLO.RS");  // 忽略 ASCII 大小写比较

find 返回的是字节索引 ,可直接用于切片:&s[..s.find('.').unwrap()]。

4.2 切分(极常用)

rust 复制代码
let s = "a,b,,c";

s.split(',');                 // 迭代器:["a", "b", "", "c"]
s.split_whitespace();         // 按任意空白切分(推荐,自动处理多余空格)
s.splitn(2, ',');             // 最多切 2 段 → ["a", "b,,c"]
s.rsplit('.');                // 从右往左切
"1\n2\n3".lines();            // 按行切(文件处理常用,见 16 章)

let mut it = s.split(',');
it.next();                    // Some("a")
it.next();                    // Some("b")

// 切分后收集成 Vec:
let parts: Vec<&str> = "a,b,c".split(',').collect();  // ["a", "b", "c"]

// 连接(Vec<&str> → String):
let joined = parts.join("-"); // "a-b-c"

4.3 遍历(理解 UTF-8 的入口)

rust 复制代码
let s = "héllo";

s.chars();                   // 迭代 char:'h', 'é', 'l', 'l', 'o'
s.bytes();                   // 迭代 u8 字节:6 个字节(é 是 2 字节)
s.char_indices();            // 迭代 (字节索引, char):(0,'h'), (1,'é'), (3,'l')...

// 两个重要事实:
// ① len() 是字节数,不是字符数:
assert_eq!(s.len(), 6);
assert_eq!(s.chars().count(), 5);   // 字符数要这样数

// ② 取"第 i 个字符"没有 O(1) 方法(UTF-8 变长编码),要么迭代,要么按字节找:
s.chars().nth(2);            // Some('l') ------ O(i)
"hello".chars().next();      // Some('h')

4.4 提取子串与解析

rust 复制代码
let s = "hello.rs";

&s[0..5];                 // "hello" ------ 切片必须在字符边界上(见第 6 节)
&s[6..];                  // "rs"
s.split_at(5);            // ("hello", ".rs")

"42".parse::<i32>();      // Ok(42) ------ 解析为数字(turbofish,见 06 章)
"3.14".parse::<f64>();    // Ok(3.14)

5. 常用转换速查表

从 → 到 方法
&str → String to_string() / String::from() / .into()
String → &str &s(deref)/ s.as_str() / &s[..]
&str → &[u8] s.as_bytes()
&[u8] → &str std::str::from_utf8(b)?(校验)
Vec<u8> → String String::from_utf8(v).unwrap()(校验)
任意字节 → 丢无效字符 String::from_utf8_lossy(b)(宽容模式)
char → String c.to_string()
数字 → 字符串 n.to_string() / format!("{n}")
字符串 → 数字 "42".parse::<i32>()

from_utf8_lossy 在处理网络/文件来的"可能不合法的 UTF-8"时特别实用------不 panic,坏字节替换成 �。

6. UTF-8 索引陷阱(最重要的坑)

6.1 不能用整数下标

ini 复制代码
let s = String::from("hello");
// let c = s[0];   // ❌ 编译错误:String 不能按 usize 索引

为什么不支持?因为 s[0] 该返回什么有歧义:第一个字节(0x68)?第一个字符('h')?为了不给"你以为取字符、实际取到半个多字节字符"的机会,Rust 干脆禁用。取字符用迭代器:

scss 复制代码
s.chars().next();       // 第一个字符
s.chars().nth(4);       // 第 5 个字符(O(n))

6.2 切片必须落在字符边界

ini 复制代码
let s = "héllo";          // h(1字节) é(2字节) l l o
&s[0..1];                 // ✅ "h",边界正确
&s[0..2];                 // ❌ panic!索引 2 落在 é 的中间
&s[0..3];                 // ✅ "hé"

处理英文 ASCII 时每个字符恰好 1 字节,不会踩坑;一旦出现中文/emoji,按字节切片就可能 panic。安全做法:先找边界或用 chars 处理:

ini 复制代码
let s = "你好";
// 取前 2 个"字符":
let first_two: String = s.chars().take(2).collect();  // "你好"

6.3 len()、truncate()、remove()、insert() 都是按字节

rust 复制代码
let mut s = String::from("你好");
assert_eq!(s.len(), 6);            // 3 字节 × 2 字

// s.truncate(4);  // ❌ panic:4 不是字符边界(第二个"好"字占 3..6)
s.truncate(3);      // ✅ "你"

s.insert(0, '嗨');  // ✅ 按字节索引插入,但索引 0 总是边界

6.4 附加:用户感知的"字符"是字素簇

"字"在不同层面含义不同:é 可以是单个 char(U+00E9),也可以是 e + 组合重音符两个 char;emoji "👨‍👩‍👧" 是 5 个 char。chars() 数的是 char(Unicode 码点),不是人眼看到的"字"。需要按字素簇切分用 unicode-segmentation crate,或者记住:面向用户的截断要用第三方库,内部处理用 chars() 即可。

7. 内存与性能

rust 复制代码
let mut s = String::with_capacity(1024);   // 预分配 1024 字节
s.push_str("hello");
assert!(s.capacity() >= 1024);
assert_eq!(s.len(), 5);                     // len 是已用字节数

// 频繁拼接的性能排序:
// ① with_capacity + push_str   最快(零重分配)
// ② format!                    简洁,一次分配
// ③ s1 + s2 + s3               左操作数被逐个 move,可能多次分配

String 扩容策略和 Vec 一样(容量不够时按倍数重新分配并拷贝),所以"预分配 + push_str"是攒大文本(如生成 HTML、拼 SQL)的标准姿势。

8. API 设计:参数用 &str,字段用 String

一条黄金法则:

rust 复制代码
// ❌ 参数用 String ------ 调用方每次都得 to_string() 分配拷贝
fn greet(name: String) { println!("Hi {name}"); }

// ✅ 参数用 &str ------ 字面量、String、&String 都能传,零拷贝
fn greet(name: &str) { println!("Hi {name}"); }

greet("Alice");                    // ✅ 字面量直接传
let owner = String::from("Bob");
greet(&owner);                     // ✅ &String 自动 deref 成 &str

同理,结构体字段存数据时用 String(拥有所有权,活得和结构体一样久);只在字段要借用外部数据时才用 &'a str(需要生命周期标注,见 08 章):

rust 复制代码
struct User {
    name: String,        // 拥有自己的数据 ------ 默认选择
}

struct Borrowed<'a> {
    name: &'a str,       // 借用别人的数据 ------ 特殊场景(零拷贝解析等)
}

9. 实战示例

9.1 词频统计(字符串 + 集合综合)

rust 复制代码
use std::collections::HashMap;

fn word_frequency(text: &str) -> HashMap<String, u32> {
    let mut freq = HashMap::new();
    for word in text.split_whitespace() {
        let word = word.trim_matches(|c: char| !c.is_alphanumeric()); // 去标点
        if word.is_empty() { continue; }
        *freq.entry(word.to_lowercase()).or_insert(0) += 1; // entry API,见 04 章
    }
    freq
}

9.2 提取文件扩展名

rust 复制代码
fn extension(path: &str) -> Option<&str> {
    let idx = path.rfind('.')?;
    Some(&path[idx + 1..])       // 返回切片借用,零拷贝
}

assert_eq!(extension("a.tar.gz"), Some("gz"));
assert_eq!(extension("noext"), None);

9.3 简易模板替换

rust 复制代码
fn render(template: &str, name: &str) -> String {
    template.replace("{{name}}", name)
}

assert_eq!(render("Hello, {{name}}!", "Rust"), "Hello, Rust!");

易错点与陷阱

  1. len() 是字节数不是字符数 :中文一个字 3 字节,emoji 4 字节。数字符用 chars().count()。
  2. 整数下标被禁用、切片可能 panic :&s[0..n] 的 n 必须落在字符边界;混有中文/emoji 时优先用 chars 迭代。
  3. + 吃掉左操作数 :s1 + &s2 后 s1 被 move。拼接一律用 format! 或 push_str。
  4. remove/insert/truncate 按字节索引:在多字节文本上索引不对会 panic。
  5. trim 返回 &str 借用 :let t = s.trim(); 后继续持有 s 可变借用会编译冲突。
  6. 函数参数写 String :逼调用方拷贝,写 &str(结构体字段才用 String)。
  7. 迭代中修改 String :先迭代收集(split/chars),再修改------借用检查器会拦住同时读写。
  8. split 空子串 :"a,,c".split(',') 会产出空串 "",别忘 filter(|s| !s.is_empty())。

最佳实践

  • 函数参数一律 &str,返回值和字段用 String ------这是生态公约(String 参数的公共 API 会被人吐槽)。
  • 拼接用 format!,攒大文本用 with_capacity + push_str。
  • 处理文本行:split_whitespace 切词、lines 切行,比手写判断 \n 可靠。
  • 涉及非 ASCII 文本的索引/截断:先想 UTF-8 边界,能用迭代器就不用下标。
  • 外部输入转字符串:不确定合法性就用 from_utf8_lossy,宁可替换字符不要 panic。
  • 比较/查找类方法(contains/starts_with/eq_ignore_ascii_case)返回 bool 且零分配,优先于 find().is_some()。

要点回顾

  • String = 拥有所有权的可变 UTF-8 缓冲区;&str = 借用的 UTF-8 视图(胖指针 ptr+len)。
  • &String 自动 deref 成 &str;参数签名用 &str,调用方零负担。
  • 所有"位置/长度"都是字节 :len()、切片、insert/remove/truncate 均按字节,必须落在字符边界,否则 panic。
  • 遍历字符用 chars()/char_indices();切分用 split/split_whitespace/lines;连接用 join/format!。
  • + 运算符 move 左操作数------拼接永远首选 format!。
  • to_string()/String::from 分配拷贝;as_str()/as_bytes() 零拷贝借用。
相关推荐
风笙9783 小时前
[Rust]复合类型
rust
风笙9783 小时前
[Rust] 所有权与引用
rust
Kapaseker7 小时前
最近用 Rust 写工具,我发现这 7 个库是真好用
rust
SomeOtherTime1 天前
第 11 讲(大结局):编译期元编程与零拷贝架构——卫生声明宏(macro_rules!)、过程宏 AST 手术刀与 Serde 零反射序列化的终极合龙
rust
SomeOtherTime1 天前
番外篇(第 12 讲):走向工业界深水区——从物理定律看 Rust 在真实工程中的“降维打击”与“阿喀琉斯之踵”
开发语言·rust
Kapaseker1 天前
Rust 桌面开发到底怎么选?先看这篇文章!
rust
奶油话梅糖1 天前
容器启停 2.5 毫秒:11 天 1,700 Star 的 Kiri,用一个 900 KB 的 PID 1 干掉了 runc 和 dockerd
前端·人工智能·rust
wflynn2 天前
GitHub 今日推荐|kiri:clone3 系统调用直达容器,2.5 毫秒启动无 runc 中间层
docker·rust·kubernetes·开源·github·containers
SomeOtherTime2 天前
第 4 讲:突破静态枷锁——智能指针(Box/Rc/Arc)与内部可变性(Cell/RefCell/UnsafeCell)的内存暗道
rust