Created
October 1, 2025 09:36
-
-
Save pastuhov/cffa3dcb61590d23c875e8a6a337751f to your computer and use it in GitHub Desktop.
This file contains hidden or 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 stack | |
| // Stack is a LIFO collection. | |
| // | |
| // Concurrency: not safe for concurrent use. | |
| type Stack[T any] struct { | |
| elements []T | |
| } | |
| func (s *Stack[T]) Push(element T) { | |
| s.elements = append(s.elements, element) | |
| } | |
| func (s *Stack[T]) Pop() (T, bool) { | |
| var zero T | |
| l := len(s.elements) | |
| if l == 0 { | |
| return zero, false | |
| } | |
| ret := s.elements[l-1] | |
| s.elements[l-1] = zero | |
| s.elements = s.elements[:l-1] | |
| return ret, true | |
| } |
This file contains hidden or 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 stack_test | |
| import ( | |
| "stack" | |
| "testing" | |
| ) | |
| func TestStack(t *testing.T) { | |
| s := &stack.Stack[int]{} | |
| s.Push(1) | |
| s.Push(2) | |
| s.Push(3) | |
| if num, _ := s.Pop(); num != 3 { | |
| t.Errorf("Expected 3, got: %v", num) | |
| } | |
| if num, _ := s.Pop(); num != 2 { | |
| t.Errorf("Expected 2, got: %v", num) | |
| } | |
| if num, _ := s.Pop(); num != 1 { | |
| t.Errorf("Expected 1, got: %v", num) | |
| } | |
| if _, ok := s.Pop(); ok == true { | |
| t.Errorf("Expected false, got: %v", ok) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment