Validate Nested Parens With Vec Stack

Match brackets with a Vec stack, pushing opens and popping closes, so mismatches report both the position and the expected closer.

RustForm Validation

Code

rustsnippet
46 lines
// 配对表:闭括号指向它要求的开括号
fn closer_for(open: char) -> Option<char> {
    match open {
        '(' => Some(')'),
        '[' => Some(']'),
        '{' => Some('}'),
        _ => None,
    }
}

fn is_open(c: char) -> bool {
    matches!(c, '(' | '[' | '{')
}

// 用 Vec 当栈:push 压入开括号,pop 弹出并比对闭括号
fn balanced(input: &str) -> Result<(), String> {
    let mut stack: Vec<(usize, char)> = Vec::new();
    for (index, ch) in input.chars().enumerate() {
        if is_open(ch) {
            stack.push((index, ch));
        } else if ch == ')' || ch == ']' || ch == '}' {
            match stack.pop() {
                Some((_, open)) if closer_for(open) == Some(ch) => {}
                Some((at, open)) => {
                    return Err(format!(
                        "position {index}: {ch} does not close {open} from position {at}"
                    ));
                }
                None => return Err(format!("position {index}: unmatched {ch}")),
            }
        }
    }
    if let Some((at, open)) = stack.last() {
        return Err(format!("unclosed {open} from position {at}"));
    }
    Ok(())
}

fn main() {
    for text in ["a(b[c]{d})e", "([]", "([)]", ")"] {
        match balanced(text) {
            Ok(()) => println!("{text:?} balanced"),
            Err(reason) => println!("{text:?} -> {reason}"),
        }
    }
}

How it works

Validate Nested Parens With Vec Stack comes down to the functions closer_for, is_open, balanced and main.

A single loop drives the file — for (index, ch) in input.chars().enumerate(). Fallible operations return Result, forcing the caller to handle both arms explicitly. A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.

What to watch for

  • No external packages — everything relies on the language’s built-in APIs.
  • Errors travel through Result; if you drop the ? operators while adapting, each call site needs its own match.

Using it

Signature: fn closer_for(open: char) -> Option<char>

Running the file executes main, which drives balanced in order.

Key statements

return Err(format!("unclosed {open} from position {at}"));
Some((_, open)) if closer_for(open) == Some(ch) => {}
Some((at, open)) => {
return Err(format!(
"position {index}: {ch} does not close {open} from position {at}"
));
}

Interactive Tools for This Topic

FAQ

What happens when a call fails?
Each fallible operation returns `Result`; nothing is silently discarded.
How do you run Validate Nested Parens With Vec Stack?
The runtime alone is enough: execute the file as a complete program.