Why does Deque.at return T instead of ?T

I understand that the implementation for zig 0.16.0 is

pub fn at(deque: *const Self, index: usize) T {
    assert(index < deque.len);
    return deque.buffer[deque.bufferIndex(index)];
}

I would have expected to be something like this.

pub fn at(deque: *const Self, index: usize) ?T {
    if(index >= deque.len) return null
    return deque.buffer[deque.bufferIndex(index)];
}

Is there a reason why the function does not return an optional? the optional would be better because it gives you the static check instead of a runtime crash.

Since this is my first question about the source code, i thought id ask first before i suggest changes.

My guess is that since the caller already has access to the deque’s length, they figure it’s up to the caller to bounds-check the index and simply assert that the caller did.
This enables cases where, for better performance, when the caller knows for certain that they don’t need to bounds-check and the index will be in bounds, the function can just blindly trust the index the caller provided.

i’d agree, except that the caller would also have access to the buffer directly and would not need to access items via access functions. I wonder if it’s just a temporary implementation on purpose

1 Like

Looks like it was done for performance improvement

Assert below is kind of guard

assert(index < deque.len);

btw i also think that ?T is better…