How do I implement a stack in Go?

A stack is a data structure that follows the Last In First Out (LIFO) principle. In Go, you can implement a stack using a slice. Below is a simple example of how to create and manage a stack in Go.

package main import "fmt" // Stack represents a stack data structure type Stack struct { items []interface{} } // Push adds an item to the top of the stack func (s *Stack) Push(item interface{}) { s.items = append(s.items, item) } // Pop removes and returns the item from the top of the stack func (s *Stack) Pop() interface{} { if len(s.items) == 0 { return nil } // Get the last item lastIndex := len(s.items) - 1 item := s.items[lastIndex] // Remove the last item s.items = s.items[:lastIndex] return item } // Peek returns the top item without removing it from the stack func (s *Stack) Peek() interface{} { if len(s.items) == 0 { return nil } return s.items[len(s.items)-1] } // IsEmpty checks if the stack is empty func (s *Stack) IsEmpty() bool { return len(s.items) == 0 } func main() { stack := Stack{} stack.Push(1) stack.Push(2) stack.Push(3) fmt.Println(stack.Pop()) // Outputs: 3 fmt.Println(stack.Peek()) // Outputs: 2 fmt.Println(stack.IsEmpty()) // Outputs: false }

stack data structure golang last in first out LIFO programming