typestar

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

  1. @TypeOf and @typeName inspect types as values.
  2. @sizeOf(f64) answers in bytes at compile time.
  3. @floatFromInt and @intCast do the conversions Zig refuses to do silently.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in comptime, step 18 of 27 in Language basics.

← Previous Next →