From d0e812a730363cd6fc8a9c2e2026c87244541060 Mon Sep 17 00:00:00 2001 From: Aadhavan Srinivasan Date: Thu, 24 Oct 2024 17:34:03 -0400 Subject: [PATCH] Return error if stack is empty --- sliceQueue.go | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/sliceQueue.go b/sliceQueue.go index ba68ebd..d54c8f6 100644 --- a/sliceQueue.go +++ b/sliceQueue.go @@ -1,8 +1,13 @@ package main +import "errors" + // Helper functions for slices, to make them behave more like stacks -func peek[T any](s []T) T { - return s[len(s)-1] +func peek[T any](s []T) (T, error) { + if len(s) < 1 { + return *new(T), errors.New("Stack empty") + } + return s[len(s)-1], nil } func pop[T any](sp *[]T) T {