实现说明
String 从末尾逐字符弹出的核心是函数 main。
while let Some(c) = path.pop() 是唯一的迭代点——其余代码顺序执行一遍。
使用要点
- 跑完文件,输出里会留下标记——
pop on empty:、after popping the filename:、popped。
常见问题
运行「String 从末尾逐字符弹出」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 pop on empty:、after popping the filename:、popped 标签标明各步骤。
核心语句
while let Some(c) = path.pop() {
if c == '/' {
break;
}
}
代码示例
fn main() {
// pop consumes one char from the end and returns Option<char>
let mut empty = String::new();
println!("pop on empty: {:?}", empty.pop());
// 逐个弹出直到分隔符:模拟回退到上一级目录
let mut path = String::from("docs/notes/2026.md");
while let Some(c) = path.pop() {
if c == '/' {
break;
}
}
println!("after popping the filename: {path}");
let mut word = String::from("stack");
let top = word.pop();
println!("popped {top:?}, left {word:?}");
}