ziglang / zig

General-purpose programming language and toolchain for maintaining robust, optimal, and reusable software.
https://ziglang.org
MIT License
34.88k stars 2.55k forks source link

Proposal: make the slice operator return an array #21960

Closed mlugg closed 2 days ago

mlugg commented 2 days ago

Background

Zig's slicing operator foo[a..b] is defined to return either a slice, or a pointer-to-array, which is essentially a slice wearing a fancy hat. In this general form, foo is always evaluated as an lvalue, so even arr[a..b] returns a slice.

This behavior is arguably inconsistent with simple indexing; arr[a] returns an element value rather than an element pointer, and I don't think anyone would argue this should change.

Proposal

foo[a..b] requires that a and b be comptime-known, and returns an array value. &foo[a..b] has status-quo slicing behavior. In other words, we change foo[a..b].* to foo[a..b], and foo[a..b] to &foo[a..b].

The main drawback to this proposal is that it is far more common to need a slice as the result, particularly since the indices a and b are often runtime-known. A key question, then, is whether needing to write & in various places makes the slicing operator more difficult to use. Another potential concern is whether this might lead people to accidentally load large array values onto the stack when they meant to just take a slice, but I would consider this fairly unlikely.

rohlem commented 2 days ago

Previously rejected (closed without comment): https://github.com/ziglang/zig/issues/14359

mlugg commented 2 days ago

Hah, I was arguing against this two years ago, funny how opinions change.

Since this was previously rejected, I'll close the issue. Andrew can re-open it if he has any particular wish to revisit this, but I'm happy enough with status quo.