Skip to content

Instantly share code, notes, and snippets.

@Hypro999
Last active August 26, 2023 05:22
Show Gist options
  • Save Hypro999/46881287c9b81af76e2871d65983410a to your computer and use it in GitHub Desktop.
Save Hypro999/46881287c9b81af76e2871d65983410a to your computer and use it in GitHub Desktop.
A quick and dirty implementation of generic Stacks in Golang.
package containers
import (
"fmt"
)
type Stack[T any] []T
func (s *Stack[T]) Push(val T) {
*s = append(*s, val)
}
func (s *Stack[T]) Pop() (T, error) {
if len(*s) == 0 {
var defaultValue T
return defaultValue, fmt.Errorf("can't pop from an empty stack")
}
top := (*s)[s.Size()-1]
*s = (*s)[:s.Size()-1]
return top, nil
}
func (s *Stack[T]) Size() int {
return len(*s)
}
func (s *Stack[T]) IsEmpty() bool {
return s.Size() == 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment