Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Keep a queue with two ends

Use std.deque.Deque for queues and breadth-first traversal. Removing the first element does not shift the remaining elements.

from std.deque import Deque

def main() -> Result[(), AllocError | IoError]:
    mut queue = Deque[(i64, i64)]()?
    queue.append((0, 0))?
    queue.append((0, 1))?
    queue.appendleft((-1, 0))?
    print(len(queue))?
    while not queue.is_empty():
        match queue.popleft():
            case Some(value):
                print(value)?
            case Nothing:
                break
    print(queue.pop())?
    Ok(())
3
(-1, 0)
(0, 0)
(0, 1)
Option[tuple[i64, i64]].Nothing

len(queue) borrows the queue and calls its shared len method, so the queue remains available for removal. The same spelling works for built-in collections and standard containers with a shared len(self) -> i64 method.

Construction and appending return Result with AllocError. End removals return Option and transfer ownership. Appending takes ownership even on failure, while the existing queue remains intact. Growth is occasional; appending within capacity and removing an end allocate nothing. clear() drops all remaining values and retains the buffer for reuse.

See the module reference for exact operations and costs. A deque is owned; it has no borrowed iterator or indexed API yet.