I'm trying to create a function that returns a type base on its parameter fn (param: var) type, the simplest example being:
// What I'm trying to do is a little different but the problem is the same
fn getType(param: var) type {
return @TypeOf(param);
}
Naively, I thought that it would work the same as @TypeOf but it doesn't.
The problem: This function doesn't work if the parameter isn't comptime known, meaning:
var value: i32 = 0;
// error: unable to evaluate constant expression
var copy1: getType(value) = 25;
// works
var copy2: @TypeOf(value) = 25;
The example above doen't work because the value of value isn't comptime known, but its type is. So I think that such function should work. Sidenote, it is possible to declare a variable of param's type
fn double(param: var) @TypeOf(param) {
// I can declare a variable of its type
var double: @TypeOf(param) = param;
return double + double;
}
What am I trying to do?
I want to create a function that will accept either struct type or instance and return a default value if a type was passed:
const Data = struct {
id: usize,
pub fn init(id: usize) @This() {
return .{ .id = id };
}
};
fn getType(param: var) type {
switch (@typeInfo(@TypeOf(param))) {
.Type => return param,
.Struct => return @TypeOf(param),
else => unreachable,
}
}
fn defaultOrInstance(param: var) getType(param) {
if (@typeInfo(@TypeOf(param)) == .Type) return Data.init(5); // default value
return param;
}
defaultOrInstance(Data) == Data { .id = 5 }
defaultOrInstance(Data.init(267)) == Data { .id = 267 }
The actual program is more complex but this gives the general idea.
I'm trying to create a function that returns a type base on its parameter
fn (param: var) type, the simplest example being:Naively, I thought that it would work the same as
@TypeOfbut it doesn't.The problem: This function doesn't work if the parameter isn't comptime known, meaning:
The example above doen't work because the value of
valueisn't comptime known, but its type is. So I think that such function should work. Sidenote, it is possible to declare a variable ofparam's typeWhat am I trying to do?
I want to create a function that will accept either struct type or instance and return a default value if a type was passed:
The actual program is more complex but this gives the general idea.