Last active
August 26, 2023 05:22
-
-
Save Hypro999/46881287c9b81af76e2871d65983410a to your computer and use it in GitHub Desktop.
A quick and dirty implementation of generic Stacks in Golang.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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