Complete the code to peek the top element of the stack safely.
fn peek(stack: &Vec<i32>) -> Option<&i32> {
stack.[1]()
}The last() method returns an Option with a reference to the last element, which is the top of the stack.
Complete the code to peek the top element and handle empty stack with unwrap_or.
fn peek_or_default(stack: &Vec<i32>) -> i32 {
*stack.[1]().unwrap_or(&0)
}last() returns an Option<&i32>. Using unwrap_or(&0) returns a reference to 0 if empty, then dereferenced to i32.
Fix the error in the peek function to return the top element correctly.
fn peek(stack: &Vec<i32>) -> Option<i32> {
stack.[1]().copied()
}last() returns Option<&i32>. Using copied() converts it to Option
Fill both blanks to peek the top element and print it if present.
fn print_top(stack: &Vec<i32>) {
if let Some(top) = stack.[1]() {
println!("Top element: {}", [2]top);
}
}last() returns Option<&i32>. To print the value, dereference with *.
Fill all three blanks to peek the top element, double it, and return the result or zero if empty.
fn double_top(stack: &Vec<i32>) -> i32 {
stack.[1]().map(|x| *x[2]2).unwrap_or([3])
}last() returns Option<&i32>. map(|x| *x * 2) doubles the value. unwrap_or(0) returns 0 if empty.
