I am using a slice as a stack.
When I do this
stack := make([]int, 0)
stack = append(stack, 1, 2, 3, 4, 5)
for len(stack) != 0 {
var a int
a, stack = stack[len(stack) - 1], stack[:len(stack) - 1]
fmt.Print(a)
}
I get the output
54321
as expected.
When I do this
stack := make([]int, 0)
stack = append(stack, 1, 2, 3, 4, 5)
a, stack := stack[len(stack) - 1], stack[:len(stack) - 1]
fmt.Println(a, len(stack))
I get the output
5 4
as expected. However, when I try to combine these by doing this
stack := make([]int, 0)
stack = append(stack, 1, 2, 3, 4, 5)
for len(stack) != 0 {
a, stack := stack[len(stack) - 1], stack[:len(stack) - 1]
fmt.Print(a)
}
the result is a compile error
unused variable 'stack'
This confuses me. I thought I could use :=
as long as at least one of the variables is being declared (in this case a
), and that stack
would just get reassigned. However I am clearly wrong. Can anybody explain why the line
a, stack := stack[len(stack) - 1], stack[:len(stack) - 1]
doesn't work in the loop, and how I can do "pop" as a one-liner in a loop?