Skip to content

@nameOf built in function #8270

@batiati

Description

@batiati

Proposal

Introduce a new built-in function @nameOf that returns the name of any declaration (fields, functions, variables, consts, etc) as a comptime []const u8.

Motivation

Even with most of comptime strings being capable of raise compiler errors, strings are not easily trackable/refactorable when the underlying declaration changes. Many IDEs have some sort of feature allowing automated code-refactoring, which would be hard to use against strings.

Simple example

//Use @nameOf
var self = @fieldParentPtr(Self, @nameOf(allocator), allocator);
const NAME = @nameOf(NAME);

// instead of a string
var self = @fieldParentPtr(Self, "allocator", allocator);
const NAME = "NAME";

Drawbacks

As a built-in function, @nameOf must be capable to accept expressions that aren't valid in normal statements, for example:

// Allow to refer to a field without a instance of MyStruct
_ = std.meta.trait.hasField(@nameOf(MyStruct.name));

Similar behavior is observed in C#'s nameOf operator.

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

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions