How can the type of a function parameter be optional?

std.builtin.Param represents a function parameter. It’s type field is ?type. Why?

2 Likes

It handles situations like when a parameter type is a function of another comptime parameter. This is the same reason that the return type can be null.

pub fn Bar(comptime T: type) type {
    return struct {
        pub usingnamespace T;
        pub const Count = 0;
    };
}

pub fn Foo (comptime T: type, comptime n: Bar(T)) Bar(T) {
    return n;
}

pub fn main() void {
    comptime {
        @compileLog(@typeInfo(@TypeOf(Foo)).Fn.params);
        @compileLog(@typeInfo(@TypeOf(Foo)).Fn.return_type);
    }
}

Compile Log Output:
@as([]const builtin.Type.Fn.Param, .{ .{.is_generic = false, .is_noalias = false, .type = type}, .{.is_generic = true, .is_noalias = false, .type = null} })
@as(?type, null)
6 Likes

This also applies to anytype.

4 Likes

Wow, very interesting. Thanks for shedding light on this!

3 Likes