Achieve syntax of casts with auto return type deduction

I want to write function which automatically receives info about expected return type from call site like @ptrCast does.

Something like:

fn main() void {
   const t: usize = magic_fun();
   const t2: f16 = magic_fun();
}

fn magic_fun() magic.call_site.expected_type {
    switch(@typeInfo(magic.call_site.expected_type)) {
           "usize" => return 10;
           "f16" => return 1.995;
    }
}

I am fairly sure the only way to implement that would be by manually passing the type as an argument.
e.g. converting to

fn main() void {
   const t = magic_fun(usize);
   const t2 = magic_fun(f16);
}

fn magic_fun(T: type) T {
    switch(T) {
           usize => return 10,
           f16 => return 1.995,
           else => @compileError("Invalid type"),
    }
}
2 Likes

Me too. It’s currently impossible. I haven’t seen any accepted proposals either. I would love to use the capture syntax that’s gonna be used for anytype:

fn fun() |CallSite| {
   ...
}

In the meantime you have to pass it manually.

2 Likes

I wonder how many @builtin functions could become just regular std library functions if this syntax were adopted. Of course I’ve no idea of the tradeoffs in language complexity, just musing.

I think a big part of builtins being builtins is that this allows the standard library to be optional and implemented in userspace, if the language put a considerable amount of these builtins into the standard library, then you would likely no longer be able to use the language to write applications that don’t depend on the standard library.

But I still would like it if we eventually get a way to write functions that use the result location type.

2 Likes

I think Zig’s lazy compilation model makes depending on the standard library less of an issue in practice.

1 Like

Having builtins gives us a clear separation between the compiler and the standard library, that is why I like it. I find it way better than other languages which create annoying magic syntax or subtly hardcode the standard library into the compiler.

3 Likes