Builtins and casts in Zig
The @-builtins: reflection on types, and casts that are always spelled out.
const std = @import("std");
pub fn main() void {
// @-builtins are the compiler's own function library.
const reading: f32 = 11.2;
std.debug.print("type: {s}\n", .{@typeName(@TypeOf(reading))});
std.debug.print("f64 takes {d} bytes\n", .{@sizeOf(f64)});
// Casts are spelled out; nothing converts silently.
const feet: i32 = 11;
const exact: f32 = @floatFromInt(feet);
std.debug.print("as float: {d:.1}\n", .{exact});
std.debug.print("widened: {d}\n", .{@as(i64, @intCast(feet))});
}
How it works
@TypeOfand@typeNameinspect types as values.@sizeOf(f64)answers in bytes at compile time.@floatFromIntand@intCastdo the conversions Zig refuses to do silently.
Keywords and builtins used here
constf32f64fni32i64pubvoid
The run, in numbers
- Lines
- 14
- Characters to type
- 485
- Tokens
- 129
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 119 seconds.
Step 3 of 3 in comptime, step 18 of 27 in Language basics.