falknerdominik
5/17/2017 - 8:33 PM

Rust Generic Stack

struct Stack<T> {
    vec: Vec<T>,
    top: usize,
}

// specification
impl<T> Stack<T> {
    fn new() -> Stack<T> {
        return Stack::<T> {
                   vec: vec![],
                   top: 0,
               };
    }
    
    fn with_capacity(cap: usize) -> Stack<T> {
        return Stack::<T> {
                   vec: Vec::<T>::with_capacity(cap),
                   top: 0,
               };
    }

    fn push(&mut self, elem: T) {
        self.vec.push(elem);
        self.top += 1;
    }

    fn pop(&mut self) -> T {
        self.top -= 1;
        return self.vec.remove(self.top);
    }

    fn is_empty(&self) -> bool {
        return self.vec.len() == 0;
    }
}

// specification
/*
impl Stack<i32> {
    fn new() -> Stack<i32> {
        return Stack::<i32> {
                   vec: vec![],
                   top: 0,
               };
    }

    fn with_capacity(cap: i32) -> Stack<i32> {
        return Stack::<i32> {
                   vec: vec![0, cap],
                   top: 0,
               };
    }

    fn push(&mut self, number: i32) {
        self.vec.push(number);
        self.top += 1;
    }

    fn pop(&mut self) -> i32 {
        self.top -= 1;
        return self.vec.remove(self.top);
    }

    fn is_empty(&self) -> bool {
        return self.vec.len()  == 0;
    }
}*/

fn main() {
    let mut s = Stack::new();
    let mut s2: Stack<String> = Stack::with_capacity(12);
    
    s2.push("HELP".to_string());

    if s.is_empty() {
        println!("vector1 is empty!");
    }
    /*if s2.is_empty() {
        println!("vector2 is empty!");
    }*/

    s.push(1);
    s.push(2);
    s.push(3);
    s.push(4);

    println!("vec is: {:?}", s.vec);

    s.pop();
    s.pop();

    println!("vec is: {:?}", s.vec);
    println!("vec 2 is: {:?}", s2.vec);

    if !s.is_empty() {
        println!("vector1 is not empty!");
    }
    /*if !s2.is_empty() {
        println!("vector2 is not empty!");
    }*/

}