Skip to content

Instantly share code, notes, and snippets.

@sausheong
Created May 16, 2022 06:25
Show Gist options
  • Save sausheong/7a7fc944c0f3598c6f64842d7bd452d5 to your computer and use it in GitHub Desktop.
Save sausheong/7a7fc944c0f3598c6f64842d7bd452d5 to your computer and use it in GitHub Desktop.
generics
type TStack[T constraints.Ordered] struct {
items []T
}
func (s *TStack[T]) Push(item T) {
s.items = append(s.items, item)
}
func (s *TStack[T]) Pop() (item T) {
if !s.IsEmpty() {
item = s.items[len(s.items)-1]
s.items = s.items[:len(s.items)-1]
}
return
}
func (s *TStack[T]) Peek() (item T) {
if !s.IsEmpty() {
item = s.items[len(s.items)-1]
}
return
}
func (s *TStack[T]) IsEmpty() bool {
return len(s.items) == 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment