From 7de370e3f934d2a26e8a3758f85b777d72482e67 Mon Sep 17 00:00:00 2001 From: Gregory Date: Wed, 15 Dec 2021 23:43:29 +0200 Subject: [PATCH] generic stack --- fundamentals/stack/stack.go | 29 ++++++++++++----------------- fundamentals/stack/stack_test.go | 6 +++--- 2 files changed, 15 insertions(+), 20 deletions(-) diff --git a/fundamentals/stack/stack.go b/fundamentals/stack/stack.go index d94296e..d464383 100644 --- a/fundamentals/stack/stack.go +++ b/fundamentals/stack/stack.go @@ -1,11 +1,6 @@ package stack -// "Generic" item. -// When type parameters will land this type became -// type Item[T any] T -type Item interface{} - -type Stack interface { +type Stack[Item any] interface { Push(Item) Pop() Item Size() int @@ -14,37 +9,37 @@ type Stack interface { // We use linked list as internal data structure // to get O(1) speed for push and pop opeartions -type node struct { +type node[Item any] struct { item Item - next *node + next *node[Item] } -type stack struct { +type stack[OfType any] struct { size int - head *node + head *node[OfType] } -func NewStack() Stack { - return &stack{} +func NewStack[OfType any]() Stack[OfType] { + return &stack[OfType]{} } -func (s *stack) Push(item Item) { +func (s *stack[Item]) Push(item Item) { next := s.head - s.head = &node{item, next} + s.head = &node[Item]{item, next} s.size++ } -func (s *stack) Pop() Item { +func (s *stack[Item]) Pop() Item { head := s.head s.head = head.next s.size-- return head.item } -func (s *stack) Size() int { +func (s *stack[_]) Size() int { return s.size } -func (s *stack) IsEmpty() bool { +func (s *stack[_]) IsEmpty() bool { return s.size == 0 } diff --git a/fundamentals/stack/stack_test.go b/fundamentals/stack/stack_test.go index d7c443a..7a540b7 100644 --- a/fundamentals/stack/stack_test.go +++ b/fundamentals/stack/stack_test.go @@ -6,18 +6,18 @@ import ( ) func TestSimple(t *testing.T) { - stack := NewStack() + stack := NewStack[int]() stack.Push(1) stack.Push(2) - if stack.Pop().(int) != 2 { + if stack.Pop() != 2 { log.Fatal("wrong stack value") } } func TestSize(t *testing.T) { - stack := NewStack() + stack := NewStack[int]() if !stack.IsEmpty() { log.Fatal("should be empty")