#how can i make a function parameter accept any float?

1 messages · Page 1 of 1 (latest)

lilac plank
#

I guess you can do a check in the body of a function like this :

fn foo(flt: anytype) void {
    _ = @typeInfo(@TypeOf(flt)).float;
    std.debug.print("foo: {any}\n", .{flt});
}

Any ints would just err

frozen wigeon
#

If you want to accept any float type

pub fn foo(x: anytype) void {
  if (@typeInfo(@TypeOf(x)) != .float) @compileError("expected float type, found " ++ @typeName(@TypeOf(x)));
  ...
}

If you want to return a specific float type

pub fn bar(comptime T: type) T {
  if (@typeInfo(T) != .float) @compileError("expected float type, found " ++ @typeName(T));
  return 0.0;
}
#

what do you want then? anytype / type is what you have to use if you want to make generic functions

#

does the code provided not accomplish what you want though? it allows only floats to be passed

coral geode
#

you want it to be more clear that it has to be a float from the function signature im guessing?

#

maybe a comment along with anytype as the parameter type will accomplish that?

lilac plank
#

In examples provided by gooncreeper compiler errors out when type is not float, hence, only possible variants of this function is with floats. It even gives a nice and friendly error message, how is it any different than other languages?

#

For more complex data types Zig has sort of interfaces , like std.Random and std.Allocator.