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.
Code
// 配对表:闭括号指向它要求的开括号
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 ownmatch.
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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.