Unable to translate vector of vector or item from python to rust

I am trying to translate the following program, which groups items by parenthesis from python to rust:

stack = [[]]

program = [x for x in "a+(b(c+d)+e+(f+(g)))"]

for token in program:
    if token == "(":
    elif token == ")":
        popped = stack.pop(); stack[-1].append(popped)

enum TokenTree {
use TokenTree::*;
impl std::fmt::Debug for TokenTree {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Parens(list) => list.fmt(f),
            Token(c) => c.fmt(f),

fn main() {
    let mut stack = vec![vec![]];
    let program = "a+(b(c+d)+e+(f+(g)))".chars();
    for token in program {
        match token {
            '(' => stack.push(vec![]),
            ')' => {
                let popped = stack.pop().unwrap();
            _ => stack.last_mut().unwrap().push(Token(token)),
    println!("{:?}", stack[0]);

Rust Playground

Or you could also derive the Debug implementation if you don't care about getting the exact same output as the python program.

(I wrote this answer on mobile, so haven't added much explanation.)

1 Like

Oh, I had the exact same code, but I didn't know about last_mut, so I have tried every possible combination of adding & and but, but to no avail. Thank you so very much!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.