A stack machine of commands in Rust

Rust interview exercise on Structs & Enums, difficulty 3 of 3. Solve it in the editor beside a worked example; the tests run the moment you do.

Write run(commands) that executes commands against a stack of i32 and returns the final stack. Push(n) pushes; Pop discards the top; Add pops two values and pushes their sum; Dup pushes a copy of the top. When a command needs more values than the stack holds, return Err("stack underflow at command N") with the zero-based index.

Each exercise pairs a worked example with a twin problem to solve in a real editor; the tests run the moment you do. Progress is saved in your browser, and in your account if you sign in.

More Structs & Enums in Rust

All Rust exercises · Other languages and frameworks