Zig Type Casting
Sooner or later you’ll have a value of one type and need another: a usize length that has to become an f64 for an average, or a big u32 you need to store in a u8. Some languages convert numbers for you without asking, which is how bugs like a negative number turning into four billion sneak in. Zig only converts on its own when nothing can go wrong. For everything else you write a cast, a builtin that says exactly what conversion you want. This page shows both, and which builtin to reach for.
Automatic conversions (coercion)
Section titled “Automatic conversions (coercion)”When a conversion can never lose information, Zig just does it. This is called type coercion:
const std = @import("std");
pub fn main() void { const small: u8 = 200; const wider: u32 = small; // u8 fits in u32 const signed: i16 = small; // every u8 value fits in i16 const precise: f64 = @as(f32, 1.5); // f32 fits in f64 const as_float: f64 = small; // every u8 value is exact in an f64 std.debug.print("{d} {d} {d} {d}\n", .{ wider, signed, precise, as_float });}Output:
200 200 1.5 200The rule is simple: if every possible value of the old type fits in the new type, the conversion is automatic. A u8 (0 to 255) fits in a u32, in an i16, and in an f64. The reference spells out each case under type coercion.
The other direction doesn’t work, even when your particular value would fit:
const std = @import("std");
pub fn main() void { var big: u32 = 42; big += 1; const small: u8 = big; std.debug.print("{d}\n", .{small});}main.zig:6:23: error: expected type 'u8', found 'u32' const small: u8 = big; ^~~main.zig:6:23: note: unsigned 8-bit int cannot represent all possible unsigned 32-bit valuesbig is 43, which fits in a u8, but the compiler checks the type, not today’s value: a u32 could be four billion. So you need a cast.
There’s one exception: a value the compiler knows at compile time. const x: u64 = 255; const y: u8 = x; works, because the compiler can see 255 fits.
@as: say which type you mean
Section titled “@as: say which type you mean”@as(T, value) converts value to type T, but only if it’s a safe coercion. Think of it as an annotation you can write in the middle of an expression:
const std = @import("std");
pub fn main() void { const level = @as(u8, 7); std.debug.print("{} {d}\n", .{ @TypeOf(level), level }); std.debug.print("{d}\n", .{@as(f64, 10) / 4});}Output:
u8 72.5In the second line, @as(f64, 10) makes the 10 an f64, so the division is float division and you get 2.5. @as can’t do anything unsafe: @as(u8, big) with a u32 gives the same error as above.
Casts take their type from where the result goes
Section titled “Casts take their type from where the result goes”Most cast builtins don’t take a type argument. They look at where the result goes, which Zig calls the result type. In const small: u8 = @intCast(big); the result goes into a u8, so that’s the target.
When there’s no such place, the compiler can’t know what you want:
const std = @import("std");
pub fn main() void { var big: u32 = 42; big += 1; const small = @intCast(big); std.debug.print("{d}\n", .{small});}main.zig:6:19: error: @intCast must have a known result type const small = @intCast(big); ^~~~~~~~~~~~~main.zig:6:19: note: use @as to provide explicit result typeFix it either with an annotation, const small: u8 = @intCast(big);, or by wrapping the cast in @as: const small = @as(u8, @intCast(big));. You’ll see the @as(T, @someCast(x)) pattern a lot in Zig code.
@intCast: integer to integer, checked
Section titled “@intCast: integer to integer, checked”@intCast converts between integer types when you know the value fits:
const std = @import("std");
pub fn main() void { var total: u32 = 40; total += 2; const percent: u8 = @intCast(total); std.debug.print("{d}%\n", .{percent});}Output:
42%You’re telling the compiler “trust me, this fits”. In debug and safe builds (zig run uses debug), Zig still checks at runtime. If you were wrong, the program stops with a clear message instead of carrying on with a garbage number:
const std = @import("std");
pub fn main() void { var total: u32 = 40; total += 260; const percent: u8 = @intCast(total); std.debug.print("{d}%\n", .{percent});}You’ll see something like:
thread 2795 panic: integer does not fit in destination typemain.zig:6:25: 0x11d2db1 in main (main.zig) const percent: u8 = @intCast(total); ^The first line says what went wrong, the second says where (file, line and column). The thread number and addresses change from run to run, and a few more lines of stack trace follow. A panic is Zig stopping the program because of a bug. In fast and small builds the check is gone, and a wrong @intCast is illegal behavior, so make sure the value really fits. Zig Integer Overflow explains the build modes.
@intCast also converts between signed and unsigned, like an i32 index into a usize. A negative value fails the check, which is exactly what you want.
@truncate: keep the low bits
Section titled “@truncate: keep the low bits”Sometimes you want to throw the high bits away, for example to split a 16-bit number into two bytes. That’s @truncate:
const std = @import("std");
pub fn main() void { var color: u16 = 0xABCD; color += 0; // keep it a runtime value const low: u8 = @truncate(color); const high: u8 = @truncate(color >> 8); std.debug.print("high 0x{x}, low 0x{x}\n", .{ high, low });}Output:
high 0xab, low 0xcd@truncate never panics: it always keeps the lowest bits that fit and drops the rest. That’s the difference from @intCast. Use @intCast when losing data would be a bug, @truncate when losing the high bits is the point.
@floatFromInt: integer to float
Section titled “@floatFromInt: integer to float”To turn an integer into a float, use @floatFromInt. You need it for any integer type that can’t always be stored exactly in the float, like usize and u64. The classic case is an average:
const std = @import("std");
pub fn main() void { var total: u64 = 0; var count: usize = 0; total += 7; count += 1; total += 8; count += 1; const average = @as(f64, @floatFromInt(total)) / @as(f64, @floatFromInt(count)); std.debug.print("average: {d}\n", .{average});}Output:
average: 7.5Why the @as(f64, ...) around each one? Writing const average: f64 = @floatFromInt(total) / @floatFromInt(count); looks fine but fails with @floatFromInt must have a known result type. The f64 annotation applies to the result of the division, and the compiler doesn’t pass it down to each side of the /. So each conversion gets its own @as(f64, ...).
Float to integer: @trunc, @round, @floor, @ceil
Section titled “Float to integer: @trunc, @round, @floor, @ceil”To turn a float into an integer, decide how to round, then use the matching builtin with an integer result type:
const std = @import("std");
pub fn main() void { var price: f64 = 9.75; price += 0; // keep it a runtime value const t: i32 = @trunc(price); const r: i32 = @round(price); const f: i32 = @floor(price); const c: i32 = @ceil(price); std.debug.print("trunc {d}, round {d}, floor {d}, ceil {d}\n", .{ t, r, f, c });}Output:
trunc 9, round 10, floor 9, ceil 10@trunc drops the decimals, @round goes to the nearest whole number, @floor rounds down and @ceil rounds up. If the result doesn’t fit in the integer type (say, 1e20 into an i32), debug builds panic with integer part of floating point value out of bounds.
@floatCast: a smaller float
Section titled “@floatCast: a smaller float”Going from f64 to f32 can lose precision, so it isn’t automatic. @floatCast does it:
const std = @import("std");
pub fn main() void { var precise: f64 = 3.14159265358979; precise += 0; const rough: f32 = @floatCast(precise); std.debug.print("f64: {d}\nf32: {d}\n", .{ precise, rough });}Output:
f64: 3.14159265358979f32: 3.1415927It doesn’t panic; it rounds to the nearest f32.
@bitCast: same bits, different type
Section titled “@bitCast: same bits, different type”@bitCast doesn’t convert the value at all. It keeps the exact bits and reads them as another type of the same size:
const std = @import("std");
pub fn main() void { var minus_one: i8 = -1; minus_one += 0; const as_unsigned: u8 = @bitCast(minus_one); std.debug.print("i8 -1 as u8: {d}\n", .{as_unsigned});
const one: f32 = 1.0; const bits: u32 = @bitCast(one); std.debug.print("bits of 1.0: 0x{x}\n", .{bits});}Output:
i8 -1 as u8: 255bits of 1.0: 0x3f800000-1 as an i8 is stored as eight 1 bits, and eight 1 bits as a u8 is 255. You’ll use @bitCast for things like hashing floats or looking at how a number is stored. Both types must be the same size, or it’s a compile error. It only works on types with a fixed bit layout: numbers, bool, enums with an integer type, packed structs and arrays of those. Zig 0.17 tightened this, so older code that bit-casts an extern struct no longer compiles. If you just want a number in a different type, you want @intCast or one of the others, not @bitCast.
Which cast do I need?
Section titled “Which cast do I need?”| From | To | Use | If it doesn’t fit |
|---|---|---|---|
| Small int | Bigger int or float | Nothing (automatic) or @as |
Can’t happen |
| Int | Smaller int | @intCast |
Panic in debug/safe builds |
| Int | Smaller int, dropping high bits | @truncate |
Not an error, bits are dropped |
| Int | Float | @floatFromInt |
Rounds to the nearest float |
| Float | Int | @trunc, @round, @floor, @ceil |
Panic in debug/safe builds |
f64 |
f32 |
@floatCast |
Rounds |
bool |
Int | @intFromBool |
Can’t happen |
| Enum | Int | @backingInt |
Can’t happen |
| Int | Enum | @fromBackingInt |
Panic in debug/safe builds if no tag has that number |
| Anything | Same-size type, same bits | @bitCast |
Size mismatch is a compile error |
The two enum rows are new in Zig 0.17: @backingInt and @fromBackingInt replace @intFromEnum and @enumFromInt, which still work but are deprecated (zig fmt even rewrites them for you). You’ll meet enums properly in Zig Enums. The reference lists every cast builtin, including the ones for pointers, under explicit casts.
Practice
Section titled “Practice”1. Percentage
Section titled “1. Percentage”You have var done: usize = 0; and var total: usize = 0;. Add 3 to done and 8 to total, then print the percentage done with one decimal: 37.5%.
Hint: convert both to f64 with @as(f64, @floatFromInt(...)), divide, multiply by 100. Print with {d:.1}.
Show solution
const std = @import("std");
pub fn main() void { var done: usize = 0; var total: usize = 0; done += 3; total += 8; const ratio = @as(f64, @floatFromInt(done)) / @as(f64, @floatFromInt(total)); std.debug.print("{d:.1}%\n", .{ratio * 100});}Output:
37.5%Dividing two usize values would give 0 (integer division). Converting both to f64 first keeps the fraction.
2. Fix the cast
Section titled “2. Fix the cast”This doesn’t build. Make it print level 12 while keeping const level = ... without a type annotation.
const std = @import("std");
pub fn main() void { var raw: u32 = 10; raw += 2; const level = @intCast(raw); std.debug.print("level {d}\n", .{level});}Hint: the cast needs a known result type. Wrap it in @as.
Show solution
const std = @import("std");
pub fn main() void { var raw: u32 = 10; raw += 2; const level = @as(u8, @intCast(raw)); std.debug.print("level {d}\n", .{level});}Output:
level 12@as(u8, ...) gives @intCast its target type. const level: u8 = @intCast(raw); would work just as well.
3. Round the price
Section titled “3. Round the price”Convert var price: f64 = 19.6; to a whole number of dollars two ways, rounding down and to the nearest, and print floor 19, nearest 20. Use price += 0; to keep it a runtime value.
Hint: @floor and @round, each into a u32.
Show solution
const std = @import("std");
pub fn main() void { var price: f64 = 19.6; price += 0; const down: u32 = @floor(price); const nearest: u32 = @round(price); std.debug.print("floor {d}, nearest {d}\n", .{ down, nearest });}Output:
floor 19, nearest 20With an integer result type, @floor and @round round the float and convert it in one step.
- Coercion is automatic when every value of the old type fits in the new one:
u8tou32,u8tof64,f32tof64. @as(T, x)makes a safe conversion explicit and gives other casts their result type.@intCastshrinks an integer and panics in safe builds if it doesn’t fit;@truncatejust drops the high bits.@floatFromIntturns an integer into a float; wrap it as@as(f64, @floatFromInt(x))inside math.@trunc,@round,@floorand@ceilturn a float into an integer.@intFromFloatis deprecated (since 0.16).@floatCastgoes from a bigger float to a smaller one;@bitCastreinterprets the same bits.
Next up: Zig Integer Overflow, what happens when a number goes past its limit, and how to handle it on purpose.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference: Casting: coercion, explicit casts and peer type resolution in one place.
- Zig language reference: Type Coercion: every automatic conversion, with examples.
- Zig language reference: @intCast: the checked integer cast and what happens when it fails.
- Zig 0.16.0 release notes: float-to-int with
@truncand friends, and why@intFromFloatis deprecated.