【Rust】スタック(push, pop)を実装する

rustのvectorのスタックはpush, popを使う

fn main() {
    
    let mut stack: Vec<i32> = Vec::new();

    stack.push(3);
    stack.push(5);
    stack.push(2);

    println!("{:?}", stack);

    let temp = stack.pop();

    println!("{:?}", temp);
    println!("{:?}", stack);
}

Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.32s
Running `target/debug/rust`
[3, 5, 2]
Some(2)
[3, 5]

最初に入れたものから取り出すにはお馴染みのVecDequeを使います。

use std::collections::VecDeque;

fn main() {
    
    let mut stack: VecDeque<i32> = VecDeque::new();

    stack.push_back(3);
    stack.push_back(5);
    stack.push_back(2);

    println!("{:?}", stack);

    let temp = stack.pop_front();

    println!("{:?}", temp);
    println!("{:?}", stack);
}

Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.57s
Running `target/debug/rust`
[3, 5, 2]
Some(3)
[5, 2]