I have a u64
value that I need to cast to i64
. @as
, @intCast
, and @truncate
all give compiler errors because not all u64
values fit into i64
. That's fair enough but in this case I need an i64
and I'm willing to accept an error/crash in the unlikely event that the value doesn't fit. Does Zig have a function or operator to do this?
Asked
Active
Viewed 137 times
0

iafisher
- 938
- 7
- 14
-
1`@as(i64, @intCast(value))` should just work. – Ali Chraghi Jul 06 '23 at 11:48
-
Why does that work but not `@intCast(i64, value)`? – iafisher Jul 06 '23 at 12:12
-
https://ziglang.org/documentation/0.10.1/#intCast because the u64 might have a value that is outside of the range of an i64 so there is no guarantee of getting the same numerical value – Dylan Reimerink Jul 06 '23 at 14:18
-
`@intCast(i64, value)` is invalid syntax – Ali Chraghi Jul 07 '23 at 17:58
1 Answers
0
In 0.11, the syntax of @intCast
(and some others) has changed slightly.
@intCast
no longer takes a type argument. Instead, you must rely on Result Location Semantics:
const x: T = e
givese
a result type ofT
@as(T, e)
givese
a result type ofT
return e
givese
a result type of the function's return typeS{ .f = e }
givese
a result type of the type of the fieldS.f
f(e)
givese
a result type of the first parameter type off
For example:
const result: i64 = @intCast(value);
or
const result = @as(i64, @intCast(value));

sigod
- 3,514
- 2
- 21
- 44