package main
import (
"errors"
"fmt"
)
type Stack struct {
items []int
}
func (s *Stack) Push(val int) {
s.items = append(s.items, val) // add item at end
}
func (s *Stack) Pop() (int, error) {
if len(s.items) == 0 {
return 0, errors.New("stack is empty") // prevent pop from empty
}
val := s.items[len(s.items)-1] // get last item
s.items = s.items[:len(s.items)-1] // remove last item
return val, nil
}
func main() {
// Direct array use
arr := []int{1, 2, 3}
arr = append(arr, 4) // push 4
fmt.Printf("Array after push: %v\n", arr)
arr = arr[:len(arr)-1] // pop top
fmt.Printf("Array after pop: %v\n", arr)
// Unsafe pop from empty array (commented out to avoid panic)
// arr = arr[:len(arr)-1]
// Using stack abstraction
stack := Stack{items: []int{1, 2, 3}}
stack.Push(4) // push 4
fmt.Printf("Stack after push: %v\n", stack.items)
val, err := stack.Pop() // pop top
if err != nil {
fmt.Println(err)
} else {
fmt.Printf("Popped from stack: %d\n", val)
}
fmt.Printf("Stack after pop: %v\n", stack.items)
}s.items = append(s.items, val) // add item at end
add new item on top of stack
if len(s.items) == 0 {
return 0, errors.New("stack is empty") // prevent pop from empty
}
check if stack is empty before popping to avoid error
val := s.items[len(s.items)-1] // get last item
s.items = s.items[:len(s.items)-1] // remove last item
retrieve and remove top item from stack
Array after push: [1 2 3 4]
Array after pop: [1 2 3]
Stack after push: [1 2 3 4]
Popped from stack: 4
Stack after pop: [1 2 3]