Skip to content

Shortcut (type inferrence) for naming enum values #683

@skyfex

Description

@skyfex

Current Progress


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

  1. When declaring a const or variable, you still need the full name:
    var foobar = myModule.Type.Ok

  2. When assigning to an already declared varible, you can use the short form:
    foobar = .Ok

  3. 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 }
  1. When calling functions, you can use the short form:
fn baz(t: Type) { ... }
baz(.Ok)
  1. Is switch statements you can use the short form:
switch(foobar) {
  .Ok  => ...,
  .NotOk => ...
}
  1. 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:

Cons:

  • Can sometimes be more vague when reading code (example: baz(Active, Enabled, On) is not much more helpful than baz(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

Metadata

Metadata

Assignees

No one assigned

    Labels

    acceptedThis proposal is planned.contributor friendlyThis issue is limited in scope and/or knowledge of Zig internals.docsproposalThis issue suggests modifications. If it also has the "accepted" label then it is planned.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions