Slice Stack Push Pop And Peek
Build a LIFO stack on a slice type: append to push, truncate to pop, and an ok return keeps empty-stack calls from ever indexing out of range.
Code
package main
import "fmt"
// a stack built on a slice: push uses append, while pop and peek check for an empty stack first
type Stack []string
func (s *Stack) Push(item string) {
*s = append(*s, item)
}
func (s *Stack) Pop() (string, bool) {
if len(*s) == 0 {
return "", false // empty stack: report via the ok flag instead of panicking
}
n := len(*s) - 1
item := (*s)[n]
*s = (*s)[:n] // truncate so the backing array stops holding the popped value
return item, true
}
func (s *Stack) Peek() (string, bool) {
if len(*s) == 0 {
return "", false
}
return (*s)[len(*s)-1], true
}
func main() {
var undo Stack
undo.Push("rename column")
undo.Push("drop index")
if top, ok := undo.Peek(); ok {
fmt.Println("peek:", top)
}
for {
item, ok := undo.Pop()
if !ok {
fmt.Println("stack drained")
break
}
fmt.Println("undo:", item)
}
}The path the data takes
Slice Stack Push Pop And Peek keeps everything in the functions Push, Pop, Peek and main.
A single loop drives the file — for.
Applying it
Entry signature: func (s *Stack) Push(item string)
The demo output is labeled (peek:, stack drained, undo:), so every printed line maps back to its originating operation.
The entry point wires Push, Peek and Pop together — run it once and the whole demo flows.
Statements that matter
func (s *Stack) Peek() (string, bool) {
if len(*s) == 0 {
return "", false
}
return (*s)[len(*s)-1], true
}
func (s *Stack) Pop() (string, bool) {
if len(*s) == 0 {
return "", false // empty stack: report via the ok flag instead of panicking
}
n := len(*s) - 1
item := (*s)[n]
*s = (*s)[:n] // truncate so the backing array stops holding the popped value
return item, true
}
func (s *Stack) Push(item string) {
*s = append(*s, item)
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Slice Stack Push Pop And Peek print when run?
- Running the file directly is enough — expect labeled output lines such as `peek:`, `stack drained`, `undo:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.