String Pop Consumes From The End

Consume a String from the end with pop, breaking at a separator to walk up a path, and observe that popping an empty String yields None harmlessly.

RustData Integrity

Code

rustsnippet
18 lines
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:?}");
}

String Pop Consumes From The End: what runs and why

String Pop Consumes From The End keeps everything in the function main.

Iteration happens inside while let Some(c) = path.pop() — everything outside it runs once.

Caveats

  • Nothing arrives from a registry; the language ships every API used.

Putting it to use

The file’s callable: fn main()

The run prints the pop on empty:, after popping the filename:, popped prefixes, one per step, so lines stay attributable.

Core lines

while let Some(c) = path.pop() {
    if c == '/' {
        break;
    }
}

Interactive Tools for This Topic

FAQ

What does String Pop Consumes From The End print when run?
Running the file directly is enough — expect labeled output lines such as `pop on empty:`, `after popping the filename:`, `popped`.