I'm trying to use slices as a queue data structure and I came up with this implementation, that results in an infinite loop. This is because queue slice doesn't get updated with sub-slice queue[1:].
func badQueue() {
queue := []int{0,1,2,3,4,5}
for len(queue) > 0 {
current, queue := queue[0], queue[1:]
fmt.Println(current, queue)
}
}
0 [1 2 3 4 5]
0 [1 2 3 4 5]
0 [1 2 3 4 5]
0 [1 2 3 4 5]
0 [1 2 3 4 5]
...
I have figured out that the issue is related to the fact that I am re-declaring current and queue (with :=) instead of assigning the value, which fixes the issue:
func goodQueue() {
queue := []int{0,1,2,3,4,5}
var current int
for len(queue) > 0 {
current, queue = queue[0], queue[1:]
fmt.Println(current, queue)
}
}
0 [1 2 3 4 5]
1 [2 3 4 5]
2 [3 4 5]
3 [4 5]
4 [5]
5 []
I know what is causing the issue, but I don't fully understand why re-declaration operation in this case is not working in the same way as assigning. Why queue is not re-declared with sub-slice of queue (queue[1:])?
Thanks!