#Getting the return type of function.

1 messages · Page 1 of 1 (latest)

urban mesa
#

Is there a way to get the return type of a function? Like imagine we have:

fn Something(T1 : type, T2 : type) type {
    // Return the type
}

fn something(v1 : T1, v2 : T2) Something(T1, T2) {
    var value : Something(T1, T2) = undefined;
    // Initialise the value above
    return value;
}

My problem is that I have to rewrite Something(T1, T2) when declaring the value variabe, is there any builtin or function to get the return type of the function? Something like @returnType?

grand grove
#
fn fn_name(v:u8) u16 { //Example function.
    return v;
}
//With TypeOf
@TypeOf(fn_name(random_value))
//With typeInfo
@typeInfo(@TypeOf(fn_name)).Fn.return_type.?

Not sure if there might also be one in std.meta

urban mesa
#

ty

compact crest
urban mesa
compact crest
#

repeating the type like Something(T1, T2) is the typical way of doing it, and it has no extra cost

urban mesa
#

Well in my case I have a more complicated expression

compact crest
#

ah yeah thats tough, would be nice as a builtin. but at least you only have to do it twice if you do this:

fn something(lots of args...) Something(lots of args...) {
  const ReturnType = Something(lots of args...);
urban mesa
grand grove
#

Tbh, I misread the question of what you wanted to do ( Not writing Something(T1, T2) type twice. I thought it was getting the return type of a function. ).
Here's a hackish way since there's no builtin @returnType for now.

fn Something(comptime T1: type, comptime T2: type) type {
    return struct { v1: T1, v2: T2 };
}
fn something(comptime T1: type, comptime T2: type, comptime ReturnType: type, v1: T1, v2: T2) ReturnType {
    const value: ReturnType = .{ .v1 = v1, .v2 = v2 };
    //...
    return value;
}
pub fn main() !void {
    @compileLog(comptime something(u8, u16, Something(u8, u16), 1, 2));
}

It involves writing the type inside the calling function.

compact crest