-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
Description
Problem
In Zig we currently have to type out the full "path" to an enum value. I.e., for the following enum:
const Type = enum {
Ok,
NotOk,
};
We have to provide the namespace (if relevant), the enum and the value name: someNamespace.Type.Ok or Type.Ok
This can get very tedious. This is en example from my testing:
nrfZig.PinCnf { .dir = nrfZig.PinCnfDir.Output,
.input = nrfZig.PinCnfInput.Disconnect,
.pull = nrfZig.PinCnfPull.Disabled,
.drive = nrfZig.PinCnfDrive.H0H1,
.sense = nrfZig.PinCnfSense.Disabled,
};
The code can feel overly verbose and repetitive. It also discourages use of enums. People might use integers or booleans instead of a descriptive enum.
Proposal
Whenever Zig can infer the enum type from the context of the code, it should. Instead of writing Type.OK , you can just type OK or .OK (one or the other, which one is up for debate)
Examples
-
When declaring a const or variable, you still need the full name:
var foobar = myModule.Type.Ok -
When assigning to an already declared varible, you can use the short form:
foobar = .Ok -
When assigning to a field in a struct, or instantiting a struct , you can use the short form:
object.foobar = .Ok
object = ObjectType { .foobar = .Ok }
- When calling functions, you can use the short form:
fn baz(t: Type) { ... }
baz(.Ok)
- Is switch statements you can use the short form:
switch(foobar) {
.Ok => ...,
.NotOk => ...
}
- When returning from a function:
fn baz(t) -> Type { return .Ok }
It should also be possible to use with these proposals: #661 and #649
Discussion
Pros:
- Encourages use of enum over boolean and magic integers
- Makes it more feasible to use enums instead of special syntax/keywords (see use a builtin enum for calling conventions instead of keywords #661 and Add endianness as one of the pointer properties #649)
- Not having to repeat yourself when writing code
Cons:
- Can sometimes be more vague when reading code (example:
baz(Active, Enabled, On)is not much more helpful thanbaz(true,true,true)) - More than one way to do something
A related idea would be to infer namespace names for other things too (like function calls). This should probably be a separate proposal.
Edit: Changed the examples from Ok to .Ok syntax