#cast usize to T

1 messages · Page 1 of 1 (latest)

low tundra
#

i want to make a function that takes the mean of a slice given it and its type

#
pub fn mean(comptime T: type, slice: []T) T {
    return sum(T, slice) / slice.len;
}
#

sum() function works fine

#

mean() doesn't work if T is f32 or f64

#

because theres a division between float and usize

#

i know about using @as(T, @floatFromInt(slice.len))

#

but then if T is not a float this doesn't work

#

i'd like to reuse this function as i'm dealing with both float and unsigned slices

vivid girder
#

I believe that std.math.lossyCast might be what you are looking for.

#
pub fn mean(comptime T: type, slice: []T) T {
    return sum(T, slice) / std.math.lossyCast(T, slice.len);
}