Skip to content

Dot syntax doesn't work on optionals calling method(?Self), but does on non-optionals calling it. #23476

@Des-Nerger

Description

@Des-Nerger

Zig Version

0.15.0-dev.208+8acedfd5b

Steps to Reproduce and Observed Behavior

// dot-syntax-on-optionals.zig

pub const Int = struct {
    @"32": i32,

    pub fn inc(maybe_i: ?Self) Self {
        return .{ .@"32" = 1 + if (maybe_i) |i| i.@"32" else 0 };
    }

    test "inc" {
        try testing.expectEqual(0, (Int{ .@"32" = -1 }).inc().@"32");
        try testing.expectEqual(1, @as(?Int, null).inc().@"32");
    }

    const Self = @This();
};

const std = @import("std");
const testing = std.testing;
test {
    testing.refAllDecls(@This());
}
$ zig test dot-syntax-on-optionals.zig
dot-syntax-on-optionals.zig:12:51: error: no field or member function named 'inc' in '?dot-syntax-on-optionals.Int'
        try testing.expectEqual(1, @as(?Int, null).inc().@"32");
                                   ~~~~~~~~~~~~~~~^~~~

Expected Behavior

Expected the both expectEqual's to compile.


... Or at least neither of them to. So that to avoid giving language users the expectation of the universal support of ?Self methods.

Remember, the language philosophy went against supporting function overloading, but what the current treatment of ?Self effectively / conceptually does, is basically defining both under the same name:

    // A method. Can be called both as `i.inc()` and `Int.inc(i)`.
    pub fn inc(i: Self) Self {
        return .{ .@"32" = 1 + i.@"32" };
    }

    // A non-method. Can only be called as `Int.inc(maybe_i)`.
    pub fn inc(maybe_i: ?Self) Self {
        return (if (maybe_i) |i| i else Int{ .@"32" = 0 }).inc();
    }

So I suggest be consistent and more explicit here. One way or another.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugObserved behavior contradicts documented or intended behavior

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions