Skip to content

Proposal: Make ambiguous field/decl access in the presence of shadowing a compile error #7942

@ifreund

Description

@ifreund

Currently Zig allows decls and fields of the same struct to share names. This is confusing, especially if the field in question is a function pointer:

const std = @import("std");

const Foo = struct {
    bar: fn () void,
    fn bar(foo: Foo) void {
        std.debug.print("decl bar called\n", .{});
    }
};

fn bar2() void {
    std.debug.print("field bar called\n", .{});
}

pub fn main() void {
    const foo = Foo{ .bar = bar2 };
    foo.bar();
}

The current rule is that the field shadows the decl, but this is non-obvious at the call-site if the user intended to call Foo.bar() instead of the function pointer stored in the field bar. It should be noted that this is technically not ambiguous as field always shadows the decl and the decl may be accessed with Foo.bar(&foo);. Nonetheless, I propose to make this a compile error as I don't think the ability to use the same name for fields and decls is a beneficial feature that outweighs the confusion and potential for errors caused by this situation.

See also: #705 #6966

Metadata

Metadata

Assignees

No one assigned

    Labels

    acceptedThis proposal is planned.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