Skip to content

Proposal: disallow direct assignment to x.? #17508

@xdBronch

Description

@xdBronch

currently zig allows the following code to compile

var x: ?u32 = null;
x.? = 10

not only is this dangerous as it causes panics in safe modes and UB in unsafe modes, but it's just plain wrong, a user should simply do x = 10 instead. for newcomers to zig this code may be a logical conclusion to come to, it seemingly synergizes well with the syntax of pointers

var y: *u32 = ...;
_ = y.*; // access the value being pointed to
y.* = ...; // reassign the value being pointed to. this is perfectly fine
...
var x: ?u32 = 10;
_ = x.?; // access the underlying value
x.? = ...; // reassign the underlying value?

@InKryption pointed out to me that x.? as an lvalue semantically is useful and should still be allowed, e.g. &x.?. if we changed the semantic meaning of x.? this would cause the unwrapped value to be a temporary and therefore yield a constant pointer.

this pattern is also extremely uncommon. using sourcegraph i counted only 11 occurrences in total, 3 of which were simply a duplicated behavior test from within zig itself across zig, zig-bootstrap, and zig-spec. see:

comptime var maybe_pos_arg: ?comptime_int = null;
inline for ("ab") |x| {
_ = x;
maybe_pos_arg = 0;
if (maybe_pos_arg.? != 0) {
@compileError("bad");
}
maybe_pos_arg.? = 10;
any other case should be trivially fixed
i see no reason for this syntax to be allowed as it silently causes incorrect code and is almost never used

Metadata

Metadata

Assignees

No one assigned

    Labels

    proposalThis issue suggests modifications. If it also has the "accepted" label then it is planned.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions