From d1205c781cf3dc0a1ff962901ccc24c080401578 Mon Sep 17 00:00:00 2001 From: Aadhavan Srinivasan Date: Sat, 26 Oct 2024 13:06:12 -0400 Subject: [PATCH] Added 'mustPop' function which panics if slice is empty --- sliceQueue.go | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/sliceQueue.go b/sliceQueue.go index d54c8f6..1ef6f07 100644 --- a/sliceQueue.go +++ b/sliceQueue.go @@ -10,8 +10,19 @@ func peek[T any](s []T) (T, error) { return s[len(s)-1], nil } -func pop[T any](sp *[]T) T { +func mustPop[T any](sp *[]T) T { + val, err := pop(sp) + if err != nil { + panic(err) + } + return val +} + +func pop[T any](sp *[]T) (T, error) { + if len(*sp) < 1 { + return *new(T), errors.New("Stack empty") + } to_return := (*sp)[len(*sp)-1] *sp = (*sp)[:len(*sp)-1] - return to_return + return to_return, nil }