package main
import "fmt"
func main() {
// Create
var stack []string
// Push
stack = append(stack, "world!")
stack = append(stack, "Hello ")
for len(stack) > 0 {
// Print top
n := len(stack) - 1
fmt.Print(stack[n])
// Pop
stack = stack[:n]
}
// Output: Hello world!
}​
Output :
Hello world!
First, we use the built-in append()
function to implement the append behavior. Then we use len(stack)-1
to select the top of the stack and print.
For pop, we set the new length of the stack to the position of the printed top value, len(stack)-1
.