#Confusion with using @as

1 messages · Page 1 of 1 (latest)

brisk orchid
#

would really appreciate help about what exactly @as does ?
specifically why does this work ?

 const t1: u8 = 45;
  _ = @as(f32,t1);

its able to convert u8 -> f32 using @as

but when I try to do

const r:f32 = @divExact( @as(f32,j),@as(f32,255));

I get an error : error: expected type 'f32', found 'u8'

this problem seems to be fixed by using @floatFromInt but isnt @as supposed to do the conversion ?

hoary hare
#

@as just provides a result type

#

same thing as const x: T = does, where T is the result type

nova heart
#

@as is for safe and unambiguous coercions. If you need to convert to a different type, then a different builtin should be used

#

For example, here you would use @floatFromInt, since you're converting from an int to a float

thorn sphinx
#

The first code works because t1 is comptime known

brisk orchid
#

so use @as when doing comptime conversions between types and
functions like @floatFromInt when doing runtime conversions ?

#

i see
@as(comptime T: type, expression) T
the docs mention that this function is comptime

lean cloud
#

@as for any coercion (runtime or comptime), @xFromX for any casting

#

theres just a special case for coercion being more lenient during comptime, since it can catch it in a compile error

#

you dont usually need to use @as though, as coercion is something that happens implicitly, like assigning to a variable or passing to a function

#

when the result type is unknown however, you can either use @as(T, expr) or use another line with const x: T = expr

brisk orchid
#

i see
that clears it up