Zig Type Casting
Type casting is changing a value from one type to another type.
Widening to a larger type is automatic
A u8 value fits in an i32. The assignment converts it on its own.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
const small: u8 = 200;
const wide: i32 = small;
try out.print("{d}\n", .{wide});
}@intCast narrows an integer
The value 42 fits in a u8. @intCast makes the smaller value.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
const big: i32 = 42;
const small: u8 = @intCast(big);
try out.print("{d}\n", .{small});
}Converting between int and float
@floatFromInt makes a float from an integer. @intFromFloat drops the fraction.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
const as_float: f64 = @floatFromInt(7);
const as_int: i32 = @intFromFloat(9.8);
try out.print("{d}\n", .{as_float / 2});
try out.print("{d}\n", .{as_int});
}Example
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
const start: u8 = 30;
const wide: i32 = start;
const total: i32 = wide + 12;
const as_float: f64 = @floatFromInt(total);
const back: i32 = @intFromFloat(as_float);
try out.print("{d}\n", .{wide});
try out.print("{d}\n", .{total});
try out.print("{d}\n", .{as_float / 4});
try out.print("{d}\n", .{back});
}Key points
- Widening: storing a small integer type into a larger integer type happens automatically.
- Narrowing: @intCast converts an integer to another integer type, such as a smaller one.
- Float from int: @floatFromInt converts an integer into a float.
- Int from float: @intFromFloat converts a float into an integer and drops the fraction.
- Fit check: @intCast stops the program when the value does not fit in the target type.
- Lost data: a conversion that drops a fraction or shrinks a type can lose information.
In this example, the u8 value 30 widens automatically into the i32 binding wide. Adding 12 gives the total 42. @floatFromInt turns 42 into a float, and dividing that float by 4 gives 10.5. @intFromFloat turns it back into 42.
Note
Zig asks for an explicit builtin when a conversion could lose data, instead of converting silently.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does @intFromFloat(6.9) give?