As a newcomer to Zig, I will be probably missing something important… But I would say, there is some problem with how optionals works in conjunction with conditionals (and in the same way, with loops, too).
In this (silly and incomplete) example:
const Foo = struct{};
fn doSomethingWithFoo(foo: *Foo) void {
// whatever
}
fn doAThing(optional_foo: ?*Foo) void {
if (optional_foo) |foo| {
doSomethingWithFoo(foo);
}
}
I want you to focus on that conditional within doAThing()
. There is that syntax that works with optional variables, allowing using the value inside that variable once it’s assured to contain a value.
Its nice to be able to do this, but most of times, you’re forced to provide different names for the variable containing the optional value and the one inside the closed function, when you don’t really care. In this example, I believe there’s no sense in naming function’s parameter optional_foo
. You would naturally name this parameter foo
, but that would clash with the name of the parameter of the closure.
If you try to name both foo
(spoiler alert, it is not allowed):
fn doAThing(foo: ?*Foo) void {
// Here, foo is ?*Foo
if (foo) |foo| { // |foo| shadows outer foo
doSomethingWithFoo(foo); // within this scope, foo is *Foo
}
}
Compiler gives an error by not allowing the shadowing of outer parameter. I don’t fully understand the rationale for this to happen, but I believe this shadowing should be allowed for this specific use case. Not only that, this would enable having this kind of syntax sugar:
fn doAThing(foo: ?*Foo) void {
if (foo) {
doSomethingWithFoo(foo);
}
}
Where an optional variable used as conditional would allow not having to write the arguments list, and compiler would assume an argument list with the name of the variable. That way, programmer’s burden of having to decide on two names is alleviated and behaviour would be similar to other languages (ie. C# or Kotlin allows usage of optional variables as if they were not optional, as long as null analysis checks null is not possible within scope).
I understand it is a very specific scenario and current implementation is way more general (ie. it allows arbitrary expressions as conditional), but I believe this pattern is quite usual (in my experience with other languages and small experiments with Zig), to let you consider this as a valid language enhancement proposal.