Builtin Functions

    Performs result.* = a + b. If overflow or underflow occurs, stores the overflowed bits in result and returns true. If no overflow or underflow occurs, returns false.

    @alignCast

    1. @alignCast(comptime alignment: u29, ptr: anytype) anytype

    ptr can be *T, fn(), ?*T, ?fn(), or []T. It returns the same type as ptr except with the alignment adjusted to the new value.

    A is added to the generated code to make sure the pointer is aligned as promised.

    1. @alignOf(comptime T: type) comptime_int

    This function returns the number of bytes that this type should be aligned to for the current target to match the C ABI. When the child type of a pointer has this alignment, the alignment can be omitted from the type.

    1. const expect = @import("std").debug.assert;
    2. comptime {
    3. assert(*u32 == *align(@alignOf(u32)) u32);
    4. }

    The result is a target-specific compile time constant. It is guaranteed to be less than or equal to @sizeOf(T).

    See also:

    1. @as(comptime T: type, expression) T

    Performs Type Coercion. This cast is allowed when the conversion is unambiguous and safe, and is the preferred way to convert between types, whenever possible.

    @asyncCall

    1. @asyncCall(frame_buffer: []align(@alignOf(@Frame(anyAsyncFunction))) u8, result_ptr, function_ptr, args: anytype) anyframe->T

    @asyncCall performs an async call on a function pointer, which may or may not be an .

    The provided frame_buffer must be large enough to fit the entire function frame. This size can be determined with @frameSize. To provide a too-small buffer invokes safety-checked .

    result_ptr is optional (null may be provided). If provided, the function call will write its result directly to the result pointer, which will be available to read after completes. Any result location provided to await will copy the result from result_ptr.

    async_struct_field_fn_pointer.zig

    1. const std = @import("std");
    2. const expect = std.testing.expect;
    3. test "async fn pointer in a struct field" {
    4. var data: i32 = 1;
    5. const Foo = struct {
    6. bar: fn (*i32) callconv(.Async) void,
    7. };
    8. var foo = Foo{ .bar = func };
    9. var bytes: [64]u8 align(@alignOf(@Frame(func))) = undefined;
    10. const f = @asyncCall(&bytes, {}, foo.bar, .{&data});
    11. try expect(data == 2);
    12. resume f;
    13. try expect(data == 4);
    14. }
    15. fn func(y: *i32) void {
    16. defer y.* += 2;
    17. y.* += 1;
    18. suspend {}
    19. }

    Shell

    1. $ zig test async_struct_field_fn_pointer.zig
    2. 1/1 test "async fn pointer in a struct field"... OK
    3. All 1 tests passed.

    1. @atomicLoad(comptime T: type, ptr: *const T, comptime ordering: builtin.AtomicOrder) T

    This builtin function atomically dereferences a pointer and returns the value.

    T must be a pointer, a bool, a float, an integer or an enum.

    See also:

    @atomicRmw

    1. @atomicRmw(comptime T: type, ptr: *T, comptime op: builtin.AtomicRmwOp, operand: T, comptime ordering: builtin.AtomicOrder) T

    This builtin function atomically modifies memory and then returns the previous value.

    T must be a pointer, a bool, a float, an integer or an enum.

    Supported operations:

    • .Xchg - stores the operand unmodified. Supports enums, integers and floats.
    • .Add - for integers, twos complement wraparound addition. Also supports .
    • .Sub - for integers, twos complement wraparound subtraction. Also supports Floats.
    • .And - bitwise and
    • .Nand - bitwise nand
    • .Or - bitwise or
    • .Xor - bitwise xor
    • .Max - stores the operand if it is larger. Supports integers and floats.
    • .Min - stores the operand if it is smaller. Supports integers and floats.

    See also:

    1. @atomicStore(comptime T: type, ptr: *T, value: T, comptime ordering: builtin.AtomicOrder) void

    This builtin function atomically stores a value.

    T must be a pointer, a bool, a float, an integer or an enum.

    See also:

    @bitCast

    1. @bitCast(comptime DestType: type, value: anytype) DestType

    Converts a value of one type to another type.

    Asserts that @sizeOf(@TypeOf(value)) == @sizeOf(DestType).

    Asserts that @typeInfo(DestType) != .Pointer. Use @ptrCast or @intToPtr if you need this.

    Can be used for these things for example:

    • Convert f32 to u32 bits
    • Convert i32 to u32 preserving twos complement

    Works at compile-time if value is known at compile time. It’s a compile error to bitcast a struct to a scalar type of the same size since structs have undefined layout. However if the struct is packed then it works.

    @bitOffsetOf

    1. @bitOffsetOf(comptime T: type, comptime field_name: []const u8) comptime_int

    Returns the bit offset of a field relative to its containing struct.

    For non , this will always be divisible by 8. For packed structs, non-byte-aligned fields will share a byte offset, but they will have different bit offsets.

    See also:

    @boolToInt

    1. @boolToInt(value: bool) u1

    Converts true to @as(u1, 1) and false to @as(u1, 0).

    If the value is known at compile-time, the return type is comptime_int instead of u1.

    @bitSizeOf

    1. @bitSizeOf(comptime T: type) comptime_int

    This function returns the number of bits it takes to store T in memory if the type were a field in a packed struct/union. The result is a target-specific compile time constant.

    This function measures the size at runtime. For types that are disallowed at runtime, such as comptime_int and type, the result is 0.

    See also:

    @breakpoint

    1. @breakpoint()

    This function inserts a platform-specific debug trap instruction which causes debuggers to break there.

    This function is only valid within function scope.

    @mulAdd

    1. @mulAdd(comptime T: type, a: T, b: T, c: T) T

    Fused multiply add, similar to (a * b) + c, except only rounds once, and is thus more accurate.

    Supports Floats and Vectors of floats.

    @byteSwap

    1. @byteSwap(comptime T: type, operand: T) T

    T must be an integer type with bit count evenly divisible by 8.

    operand may be an or vector.

    Swaps the byte order of the integer. This converts a big endian integer to a little endian integer, and converts a little endian integer to a big endian integer.

    Note that for the purposes of memory layout with respect to endianness, the integer type should be related to the number of bytes reported by bytes. This is demonstrated with u24. @sizeOf(u24) == 4, which means that a u24 stored in memory takes 4 bytes, and those 4 bytes are what are swapped on a little vs big endian system. On the other hand, if T is specified to be u24, then only 3 bytes are reversed.

    1. @bitReverse(comptime T: type, integer: T) T

    T accepts any integer type.

    Reverses the bitpattern of an integer value, including the sign bit if applicable.

    For example 0b10110110 (u8 = 182, i8 = -74) becomes 0b01101101 (u8 = 109, i8 = 109).

    1. @offsetOf(comptime T: type, comptime field_name: []const u8) comptime_int

    Returns the byte offset of a field relative to its containing struct.

    See also:

    @call

    1. @call(options: std.builtin.CallOptions, function: anytype, args: anytype) anytype

    Calls a function, in the same way that invoking an expression with parentheses does:

    call.zig

    1. const expect = @import("std").testing.expect;
    2. test "noinline function call" {
    3. try expect(@call(.{}, add, .{3, 9}) == 12);
    4. }
    5. fn add(a: i32, b: i32) i32 {
    6. return a + b;
    7. }

    Shell

    1. $ zig test call.zig
    2. 1/1 test "noinline function call"... OK
    3. All 1 tests passed.

    @call allows more flexibility than normal function call syntax does. The CallOptions struct is reproduced here:

    builtin.CallOptions struct

    1. pub const CallOptions = struct {
    2. modifier: Modifier = .auto,
    3. /// Only valid when `Modifier` is `Modifier.async_kw`.
    4. stack: ?[]align(std.Target.stack_align) u8 = null,
    5. pub const Modifier = enum {
    6. /// Equivalent to function call syntax.
    7. auto,
    8. /// Equivalent to async keyword used with function call syntax.
    9. async_kw,
    10. /// Prevents tail call optimization. This guarantees that the return
    11. /// address will point to the callsite, as opposed to the callsite's
    12. /// callsite. If the call is otherwise required to be tail-called
    13. /// or inlined, a compile error is emitted instead.
    14. never_tail,
    15. /// Guarantees that the call will not be inlined. If the call is
    16. /// otherwise required to be inlined, a compile error is emitted instead.
    17. never_inline,
    18. /// Asserts that the function call will not suspend. This allows a
    19. /// non-async function to call an async function.
    20. no_async,
    21. /// Guarantees that the call will be generated with tail call optimization.
    22. /// If this is not possible, a compile error is emitted instead.
    23. always_tail,
    24. /// Guarantees that the call will inlined at the callsite.
    25. /// If this is not possible, a compile error is emitted instead.
    26. always_inline,
    27. /// Evaluates the call at compile-time. If the call cannot be completed at
    28. /// compile-time, a compile error is emitted instead.
    29. compile_time,
    30. };
    31. };

    @cDefine

    1. @cDefine(comptime name: []u8, value)

    This function can only occur inside @cImport.

    This appends #define $name $value to the @cImport temporary buffer.

    To define without a value, like this:

    1. #define _GNU_SOURCE

    Use the void value, like this:

    1. @cDefine("_GNU_SOURCE", {})

    See also:

    1. @cImport(expression) type

    This function parses C code and imports the functions, types, variables, and compatible macro definitions into a new empty struct type, and then returns that type.

    expression is interpreted at compile time. The builtin functions @cInclude, @cDefine, and @cUndef work within this expression, appending to a temporary buffer which is then parsed as C code.

    Usually you should only have one @cImport in your entire application, because it saves the compiler from invoking clang multiple times, and prevents inline functions from being duplicated.

    Reasons for having multiple @cImport expressions would be:

    • To avoid a symbol collision, for example if foo.h and bar.h both #define CONNECTION_COUNT
    • To analyze the C code with different preprocessor defines

    See also:

    1. @cInclude(comptime path: []u8)

    This function can only occur inside @cImport.

    This appends #include <$path>\n to the c_import temporary buffer.

    See also:

    1. @clz(comptime T: type, operand: T)

    T must be an integer type.

    operand may be an integer or .

    This function counts the number of most-significant (leading in a big-Endian sense) zeroes in an integer.

    If operand is a comptime-known integer, the return type is comptime_int. Otherwise, the return type is an unsigned integer or vector of unsigned integers with the minimum number of bits that can represent the bit count of the integer type.

    If operand is zero, @clz returns the bit width of integer type T.

    See also:

    @cmpxchgStrong

    1. @cmpxchgStrong(comptime T: type, ptr: *T, expected_value: T, new_value: T, success_order: AtomicOrder, fail_order: AtomicOrder) ?T

    This function performs a strong atomic compare exchange operation. It’s the equivalent of this code, except atomic:

    test.zig

    1. fn cmpxchgStrongButNotAtomic(comptime T: type, ptr: *T, expected_value: T, new_value: T) ?T {
    2. const old_value = ptr.*;
    3. if (old_value == expected_value) {
    4. ptr.* = new_value;
    5. return null;
    6. } else {
    7. return old_value;
    8. }
    9. }

    If you are using cmpxchg in a loop, is the better choice, because it can be implemented more efficiently in machine instructions.

    T must be a pointer, a bool, a float, an integer or an enum.

    @typeInfo(@TypeOf(ptr)).Pointer.alignment must be >= @sizeOf(T).

    See also:

    @cmpxchgWeak

    1. @cmpxchgWeak(comptime T: type, ptr: *T, expected_value: T, new_value: T, success_order: AtomicOrder, fail_order: AtomicOrder) ?T

    This function performs a weak atomic compare exchange operation. It’s the equivalent of this code, except atomic:

    cmpxchgWeakButNotAtomic

    1. fn cmpxchgWeakButNotAtomic(comptime T: type, ptr: *T, expected_value: T, new_value: T) ?T {
    2. const old_value = ptr.*;
    3. if (old_value == expected_value and usuallyTrueButSometimesFalse()) {
    4. ptr.* = new_value;
    5. return null;
    6. } else {
    7. return old_value;
    8. }
    9. }

    If you are using cmpxchg in a loop, the sporadic failure will be no problem, and cmpxchgWeak is the better choice, because it can be implemented more efficiently in machine instructions. However if you need a stronger guarantee, use .

    T must be a pointer, a bool, a float, an integer or an enum.

    @typeInfo(@TypeOf(ptr)).Pointer.alignment must be >= @sizeOf(T).

    See also:

    1. @compileError(comptime msg: []u8)

    This function, when semantically analyzed, causes a compile error with the message msg.

    There are several ways that code avoids being semantically checked, such as using if or switch with compile time constants, and comptime functions.

    1. @compileLog(args: ...)

    This function prints the arguments passed to it at compile-time.

    To prevent accidentally leaving compile log statements in a codebase, a compilation error is added to the build, pointing to the compile log statement. This error prevents code from being generated, but does not otherwise interfere with analysis.

    This function can be used to do “printf debugging” on compile-time executing code.

    test.zig

    1. const print = @import("std").debug.print;
    2. const num1 = blk: {
    3. var val1: i32 = 99;
    4. @compileLog("comptime val1 = ", val1);
    5. val1 = val1 + 1;
    6. break :blk val1;
    7. };
    8. test "main" {
    9. @compileLog("comptime in main");
    10. print("Runtime in main, num1 = {}.\n", .{num1});
    11. }

    Shell

    1. $ zig test test.zig
    2. | *"comptime in main"
    3. | *"comptime val1 = ", 99
    4. ./docgen_tmp/test.zig:11:5: error: found compile log statement
    5. @compileLog("comptime in main");
    6. ^
    7. ./docgen_tmp/test.zig:1:35: note: referenced here
    8. const print = @import("std").debug.print;
    9. ^
    10. ./docgen_tmp/test.zig:13:5: note: referenced here
    11. print("Runtime in main, num1 = {}.\n", .{num1});
    12. ^
    13. ./docgen_tmp/test.zig:5:5: error: found compile log statement
    14. @compileLog("comptime val1 = ", val1);
    15. ^
    16. ./docgen_tmp/test.zig:13:46: note: referenced here
    17. print("Runtime in main, num1 = {}.\n", .{num1});
    18. ^

    will output:

    If all @compileLog calls are removed or not encountered by analysis, the program compiles successfully and the generated executable prints:

    without_compileLog.zig

    1. const print = @import("std").debug.print;
    2. const num1 = blk: {
    3. var val1: i32 = 99;
    4. val1 = val1 + 1;
    5. break :blk val1;
    6. };
    7. test "main" {
    8. print("Runtime in main, num1 = {}.\n", .{num1});
    9. }

    Shell

    1. $ zig test without_compileLog.zig
    2. 1/1 test "main"... Runtime in main, num1 = 100.
    3. OK
    4. All 1 tests passed.

    1. @ctz(comptime T: type, operand: T)

    T must be an integer type.

    operand may be an integer or .

    This function counts the number of least-significant (trailing in a big-Endian sense) zeroes in an integer.

    If operand is a comptime-known integer, the return type is comptime_int. Otherwise, the return type is an unsigned integer or vector of unsigned integers with the minimum number of bits that can represent the bit count of the integer type.

    If operand is zero, @ctz returns the bit width of integer type T.

    See also:

    @cUndef

    1. @cUndef(comptime name: []u8)

    This function can only occur inside @cImport.

    This appends #undef $name to the @cImport temporary buffer.

    See also:

    @divExact

    1. @divExact(numerator: T, denominator: T) T

    Exact division. Caller guarantees denominator != 0 and @divTrunc(numerator, denominator) * denominator == numerator.

    • @divExact(6, 3) == 2
    • @divExact(a, b) * b == a

    For a function that returns a possible error code, use @import("std").math.divExact.

    See also:

    @divFloor

    1. @divFloor(numerator: T, denominator: T) T

    Floored division. Rounds toward negative infinity. For unsigned integers it is the same as numerator / denominator. Caller guarantees denominator != 0 and .

    • @divFloor(-5, 3) == -2
    • (@divFloor(a, b) * b) + @mod(a, b) == a

    For a function that returns a possible error code, use @import("std").math.divFloor.

    See also:

    @divTrunc

    1. @divTrunc(numerator: T, denominator: T) T

    Truncated division. Rounds toward zero. For unsigned integers it is the same as numerator / denominator. Caller guarantees denominator != 0 and !(@typeInfo(T) == .Int and T.is_signed and numerator == std.math.minInt(T) and denominator == -1).

    • @divTrunc(-5, 3) == -1
    • (@divTrunc(a, b) * b) + @rem(a, b) == a

    For a function that returns a possible error code, use @import("std").math.divTrunc.

    See also:

    @embedFile

    1. @embedFile(comptime path: []const u8) *const [N:0]u8

    This function returns a compile time constant pointer to null-terminated, fixed-size array with length equal to the byte count of the file given by path. The contents of the array are the contents of the file. This is equivalent to a with the file contents.

    path is absolute or relative to the current file, just like @import.

    See also:

    @enumToInt

    1. @enumToInt(enum_or_tagged_union: anytype) anytype

    If there is only one possible enum value, the result is a comptime_int known at .

    See also:

    @errorName

    1. @errorName(err: anyerror) [:0]const u8

    This function returns the string representation of an error. The string representation of error.OutOfMem is "OutOfMem".

    If there are no calls to @errorName in an entire application, or all calls have a compile-time known value for err, then no error name table will be generated.

    @errorReturnTrace

    1. @errorReturnTrace() ?*builtin.StackTrace

    If the binary is built with error return tracing, and this function is invoked in a function that calls a function with an error or error union return type, returns a stack trace object. Otherwise returns .

    1. @errorToInt(err: anytype) std.meta.Int(.unsigned, @sizeOf(anyerror) * 8)

    Supports the following types:

    Converts an error to the integer representation of an error.

    It is generally recommended to avoid this cast, as the integer representation of an error is not stable across source code changes.

    See also:

    1. @errSetCast(comptime T: DestType, value: anytype) DestType

    Converts an error value from one error set to another error set. Attempting to convert an error which is not in the destination error set results in safety-protected Undefined Behavior.

    @export

    1. @export(declaration, comptime options: std.builtin.ExportOptions) void

    Creates a symbol in the output object file.

    declaration must be one of two things:

    • An identifier (x) identifying a or a variable.
    • Field access (x.y) looking up a or a variable.

    This builtin can be called from a block to conditionally export symbols. When declaration is a function with the C calling convention and options.linkage is Strong, this is equivalent to the export keyword used on a function:

    test.zig

    1. comptime {
    2. @export(internalName, .{ .name = "foo", .linkage = .Strong });
    3. }
    4. fn internalName() callconv(.C) void {}

    Shell

    1. $ zig build-obj test.zig

    This is equivalent to:

    test.zig

    Shell

    1. $ zig build-obj test.zig

    Note that even when using export, @"foo" syntax can be used to choose any string for the symbol name:

    test.zig

    1. export fn @"A function name that is a complete sentence."() void {}

    Shell

    1. $ zig build-obj test.zig

    When looking at the resulting object, you can see the symbol is used verbatim:

    1. 00000000000001f0 T A function name that is a complete sentence.

    See also:

    @extern

    1. @extern(T: type, comptime options: std.builtin.ExternOptions) *T

    Creates a reference to an external symbol in the output object file.

    See also:

    1. @fence(order: AtomicOrder)

    The fence function is used to introduce happens-before edges between operations.

    AtomicOrder can be found with @import("std").builtin.AtomicOrder.

    See also:

    @field

    1. @field(lhs: anytype, comptime field_name: []const u8) (field)

    Performs field access by a compile-time string. Works on both fields and declarations.

    field_decl_access_by_string.zig

    1. const std = @import("std");
    2. const Point = struct {
    3. x: u32,
    4. y: u32,
    5. pub var z: u32 = 1;
    6. };
    7. test "field access by string" {
    8. const expect = std.testing.expect;
    9. var p = Point{ .x = 0, .y = 0 };
    10. @field(p, "x") = 4;
    11. @field(p, "y") = @field(p, "x") + 1;
    12. try expect(@field(p, "x") == 4);
    13. try expect(@field(p, "y") == 5);
    14. }
    15. test "decl access by string" {
    16. const expect = std.testing.expect;
    17. try expect(@field(Point, "z") == 1);
    18. @field(Point, "z") = 2;
    19. try expect(@field(Point, "z") == 2);
    20. }

    Shell

    1. $ zig test field_decl_access_by_string.zig
    2. 1/2 test "field access by string"... OK
    3. 2/2 test "decl access by string"... OK
    4. All 2 tests passed.

    @fieldParentPtr

    1. @fieldParentPtr(comptime ParentType: type, comptime field_name: []const u8,
    2. field_ptr: *T) *ParentType

    Given a pointer to a field, returns the base pointer of a struct.

    @floatCast

    1. @floatCast(comptime DestType: type, value: anytype) DestType

    Convert from one float type to another. This cast is safe, but may cause the numeric value to lose precision.

    @floatToInt

    1. @floatToInt(comptime DestType: type, float: anytype) DestType

    Converts the integer part of a floating point number to the destination type.

    If the integer part of the floating point number cannot fit in the destination type, it invokes safety-checked .

    See also:

    @frame

    1. @frame() *@Frame(func)

    This function returns a pointer to the frame for a given function. This type can be to anyframe->T and to anyframe, where T is the return type of the function in scope.

    This function does not mark a suspension point, but it does cause the function in scope to become an async function.

    @Frame

    1. @Frame(func: anytype) type

    This function returns the frame type of a function. This works for as well as any function without a specific calling convention.

    This type is suitable to be used as the return type of async which allows one to, for example, heap-allocate an async function frame:

    heap_allocated_frame.zig

    1. const std = @import("std");
    2. test "heap allocated frame" {
    3. const frame = try std.heap.page_allocator.create(@Frame(func));
    4. frame.* = async func();
    5. }
    6. fn func() void {
    7. suspend {}
    8. }

    Shell

    1. $ zig test heap_allocated_frame.zig
    2. 1/1 test "heap allocated frame"... OK
    3. All 1 tests passed.

    @frameAddress

    1. @frameAddress() usize

    This function returns the base pointer of the current stack frame.

    The implications of this are target specific and not consistent across all platforms. The frame address may not be available in release mode due to aggressive optimizations.

    This function is only valid within function scope.

    @frameSize

    1. @frameSize() usize

    This is the same as @sizeOf(@Frame(func)), where func may be runtime-known.

    This function is typically used in conjunction with .

    1. @hasDecl(comptime Container: type, comptime name: []const u8) bool

    Returns whether or not a struct, , or union has a declaration matching name.

    hasDecl.zig

    1. const std = @import("std");
    2. const expect = std.testing.expect;
    3. const Foo = struct {
    4. nope: i32,
    5. pub var blah = "xxx";
    6. const hi = 1;
    7. };
    8. test "@hasDecl" {
    9. try expect(@hasDecl(Foo, "blah"));
    10. // Even though `hi` is private, @hasDecl returns true because this test is
    11. // in the same file scope as Foo. It would return false if Foo was declared
    12. // in a different file.
    13. try expect(@hasDecl(Foo, "hi"));
    14. // @hasDecl is for declarations; not fields.
    15. try expect(!@hasDecl(Foo, "nope"));
    16. try expect(!@hasDecl(Foo, "nope1234"));
    17. }

    Shell

    1. $ zig test hasDecl.zig
    2. 1/1 test "@hasDecl"... OK
    3. All 1 tests passed.

    See also:

    1. @hasField(comptime Container: type, comptime name: []const u8) bool

    Returns whether the field name of a struct, union, or enum exists.

    The result is a compile time constant.

    It does not include functions, variables, or constants.

    See also:

    @import

    1. @import(comptime path: []u8) type

    This function finds a zig file corresponding to path and adds it to the build, if it is not already added.

    Zig source files are implicitly structs, with a name equal to the file’s basename with the extension truncated. @import returns the struct type corresponding to the file.

    Declarations which have the pub keyword may be referenced from a different source file than the one they are declared in.

    path can be a relative path or it can be the name of a package. If it is a relative path, it is relative to the file that contains the @import function call.

    The following packages are always available:

    • @import("std") - Zig Standard Library
    • @import("builtin") - Target-specific information The command zig build-exe --show-builtin outputs the source to stdout for reference.

    See also:

    @intCast

    1. @intCast(comptime DestType: type, int: anytype) DestType

    Converts an integer to another integer while keeping the same numerical value. Attempting to convert a number which is out of range of the destination type results in safety-protected .

    If T is comptime_int, then this is semantically equivalent to Type Coercion.

    @intToEnum

    1. @intToEnum(comptime DestType: type, integer: anytype) DestType

    Converts an integer into an value.

    Attempting to convert an integer which represents no value in the chosen enum type invokes safety-checked Undefined Behavior.

    See also:

    1. @intToError(value: std.meta.Int(.unsigned, @sizeOf(anyerror) * 8)) anyerror

    Converts from the integer representation of an error into The Global Error Set type.

    It is generally recommended to avoid this cast, as the integer representation of an error is not stable across source code changes.

    Attempting to convert an integer that does not correspond to any error results in safety-protected .

    See also:

    @intToFloat

    1. @intToFloat(comptime DestType: type, int: anytype) DestType

    Converts an integer to the closest floating point representation. To convert the other way, use . This cast is always safe.

    1. @intToPtr(comptime DestType: type, address: usize) DestType

    Converts an integer to a pointer. To convert the other way, use .

    If the destination pointer type does not allow address zero and address is zero, this invokes safety-checked Undefined Behavior.

    @maximum

    1. @maximum(a: T, b: T) T

    Returns the maximum value of a and b. This builtin accepts integers, floats, and vectors of either. In the latter case, the operation is performed element wise.

    NaNs are handled as follows: if one of the operands of a (pairwise) operation is NaN, the other operand is returned. If both operands are NaN, NaN is returned.

    See also:

    @memcpy

    1. @memcpy(noalias dest: [*]u8, noalias source: [*]const u8, byte_count: usize)

    This function copies bytes from one region of memory to another. dest and source are both pointers and must not overlap.

    This function is a low level intrinsic with no safety mechanisms. Most code should not use this function, instead using something like this:

    1. for (source[0..byte_count]) |b, i| dest[i] = b;

    The optimizer is intelligent enough to turn the above snippet into a memcpy.

    There is also a standard library function for this:

    1. const mem = @import("std").mem;
    2. mem.copy(u8, dest[0..byte_count], source[0..byte_count]);

    @memset

    1. @memset(dest: [*]u8, c: u8, byte_count: usize)

    This function sets a region of memory to c. dest is a pointer.

    This function is a low level intrinsic with no safety mechanisms. Most code should not use this function, instead using something like this:

    1. for (dest[0..byte_count]) |*b| b.* = c;

    The optimizer is intelligent enough to turn the above snippet into a memset.

    There is also a standard library function for this:

    1. const mem = @import("std").mem;
    2. mem.set(u8, dest, c);

    @minimum

    1. @minimum(a: T, b: T) T

    Returns the minimum value of a and b. This builtin accepts integers, floats, and vectors of either. In the latter case, the operation is performed element wise.

    NaNs are handled as follows: if one of the operands of a (pairwise) operation is NaN, the other operand is returned. If both operands are NaN, NaN is returned.

    See also:

    @wasmMemorySize

    1. @wasmMemorySize(index: u32) u32

    This function returns the size of the Wasm memory identified by index as an unsigned value in units of Wasm pages. Note that each Wasm page is 64KB in size.

    This function is a low level intrinsic with no safety mechanisms usually useful for allocator designers targeting Wasm. So unless you are writing a new allocator from scratch, you should use something like @import("std").heap.WasmPageAllocator.

    See also:

    1. @wasmMemoryGrow(index: u32, delta: u32) i32

    This function increases the size of the Wasm memory identified by index by delta in units of unsigned number of Wasm pages. Note that each Wasm page is 64KB in size. On success, returns previous memory size; on failure, if the allocation fails, returns -1.

    This function is a low level intrinsic with no safety mechanisms usually useful for allocator designers targeting Wasm. So unless you are writing a new allocator from scratch, you should use something like @import("std").heap.WasmPageAllocator.

    wasmMemoryGrow.zig

    1. const std = @import("std");
    2. const native_arch = @import("builtin").target.cpu.arch;
    3. const expect = std.testing.expect;
    4. test "@wasmMemoryGrow" {
    5. if (native_arch != .wasm32) return error.SkipZigTest;
    6. var prev = @wasmMemorySize(0);
    7. try expect(prev == @wasmMemoryGrow(0, 1));
    8. try expect(prev + 1 == @wasmMemorySize(0));
    9. }

    Shell

    1. $ zig test wasmMemoryGrow.zig
    2. 1/1 test "@wasmMemoryGrow"... test "@wasmMemoryGrow"... SKIP
    3. SKIP
    4. 0 passed; 1 skipped; 0 failed.

    See also:

    @mod

    1. @mod(numerator: T, denominator: T) T

    Modulus division. For unsigned integers this is the same as numerator % denominator. Caller guarantees denominator > 0.

    • @mod(-5, 3) == 1
    • (@divFloor(a, b) * b) + @mod(a, b) == a

    For a function that returns an error code, see @import("std").math.mod.

    See also:

    1. @mulWithOverflow(comptime T: type, a: T, b: T, result: *T) bool

    Performs result.* = a * b. If overflow or underflow occurs, stores the overflowed bits in result and returns true. If no overflow or underflow occurs, returns false.

    1. @panic(message: []const u8) noreturn

    Invokes the panic handler function. By default the panic handler function calls the public panic function exposed in the root source file, or if there is not one specified, the std.builtin.default_panic function from std/builtin.zig.

    Generally it is better to use @import("std").debug.panic. However, @panic can be useful for 2 scenarios:

    • From library code, calling the programmer’s panic function if they exposed one in the root source file.
    • When mixing C and Zig code, calling the canonical panic implementation across multiple .o files.

    See also:

    @popCount

    1. @popCount(comptime T: type, operand: T)

    T must be an integer type.

    operand may be an or vector.

    Counts the number of bits set in an integer.

    If operand is a -known integer, the return type is comptime_int. Otherwise, the return type is an unsigned integer or vector of unsigned integers with the minimum number of bits that can represent the bit count of the integer type.

    See also:

    1. @prefetch(ptr: anytype, comptime options: std.builtin.PrefetchOptions)

    This builtin tells the compiler to emit a prefetch instruction if supported by the target CPU. If the target CPU does not support the requested prefetch instruction, this builtin is a noop. This function has no effect on the behavior of the program, only on the performance characteristics.

    The ptr argument may be any pointer type and determines the memory address to prefetch. This function does not dereference the pointer, it is perfectly legal to pass a pointer to invalid memory to this function and no illegal behavior will result.

    The options argument is the following struct:

    builtin.zig

    1. /// This data structure is used by the Zig language code generation and
    2. /// therefore must be kept in sync with the compiler implementation.
    3. pub const PrefetchOptions = struct {
    4. /// Whether the prefetch should prepare for a read or a write.
    5. rw: Rw = .read,
    6. /// 0 means no temporal locality. That is, the data can be immediately
    7. /// dropped from the cache after it is accessed.
    8. ///
    9. /// 3 means high temporal locality. That is, the data should be kept in
    10. /// the cache as it is likely to be accessed again soon.
    11. locality: u2 = 3,
    12. /// The cache that the prefetch should be preformed on.
    13. cache: Cache = .data,
    14. pub const Rw = enum {
    15. read,
    16. write,
    17. };
    18. pub const Cache = enum {
    19. instruction,
    20. data,
    21. };
    22. };

    1. @ptrCast(comptime DestType: type, value: anytype) DestType

    Converts a pointer of one type to a pointer of another type.

    Optional Pointers are allowed. Casting an optional pointer which is to a non-optional pointer invokes safety-checked Undefined Behavior.

    @ptrToInt

    1. @ptrToInt(value: anytype) usize

    Converts value to a usize which is the address of the pointer. value can be one of these types:

    • *T
    • ?*T
    • fn()
    • ?fn()

    To convert the other way, use

    1. @rem(numerator: T, denominator: T) T

    Remainder division. For unsigned integers this is the same as numerator % denominator. Caller guarantees denominator > 0.

    • (@divTrunc(a, b) * b) + @rem(a, b) == a

    See also:

    1. @returnAddress() usize

    This function returns the address of the next machine code instruction that will be executed when the current function returns.

    The implications of this are target specific and not consistent across all platforms.

    This function is only valid within function scope. If the function gets inlined into a calling function, the returned address will apply to the calling function.

    @select

    1. @select(comptime T: type, pred: std.meta.Vector(len, bool), a: std.meta.Vector(len, T), b: std.meta.Vector(len, T)) std.meta.Vector(len, T)

    Selects values element-wise from a or b based on pred. If pred[i] is true, the corresponding element in the result will be a[i] and otherwise b[i].

    See also:

    1. @setAlignStack(comptime alignment: u29)

    Ensures that a function will have a stack alignment of at least alignment bytes.

    1. @setCold(is_cold: bool)

    Tells the optimizer that a function is rarely called.

    Changes the maximum number of backwards branches that compile-time code execution can use before giving up and making a compile error.

    If the new_quota is smaller than the default quota (1000) or a previously explicitly set quota, it is ignored.

    Example:

    test.zig

    1. test "foo" {
    2. comptime {
    3. var i = 0;
    4. while (i < 1001) : (i += 1) {}
    5. }
    6. }

    Shell

    1. $ zig test test.zig
    2. ./docgen_tmp/test.zig:4:9: error: evaluation exceeded 1000 backwards branches
    3. while (i < 1001) : (i += 1) {}
    4. ^
    5. ./docgen_tmp/test.zig:1:12: note: referenced here
    6. test "foo" {
    7. ^

    Now we use @setEvalBranchQuota:

    setEvalBranchQuota.zig

    1. test "foo" {
    2. comptime {
    3. @setEvalBranchQuota(1001);
    4. var i = 0;
    5. while (i < 1001) : (i += 1) {}
    6. }
    7. }

    Shell

    1. $ zig test setEvalBranchQuota.zig
    2. 1/1 test "foo"... OK
    3. All 1 tests passed.

    See also:

    @setFloatMode

    Sets the floating point mode of the current scope. Possible values are:

    test.zig

    1. pub const FloatMode = enum {
    2. Strict,
    3. Optimized,
    4. };
    • Strict (default) - Floating point operations follow strict IEEE compliance.
    • Optimized - Floating point operations may do all of the following:

      • Assume the arguments and result are not NaN. Optimizations are required to retain defined behavior over NaNs, but the value of the result is undefined.
      • Assume the arguments and result are not +/-Inf. Optimizations are required to retain defined behavior over +/-Inf, but the value of the result is undefined.
      • Treat the sign of a zero argument or result as insignificant.
      • Use the reciprocal of an argument rather than perform division.
      • Perform floating-point contraction (e.g. fusing a multiply followed by an addition into a fused multiply-and-add).
      • Perform algebraically equivalent transformations that may change results in floating point (e.g. reassociate).

      This is equivalent to -ffast-math in GCC.

    The floating point mode is inherited by child scopes, and can be overridden in any scope. You can set the floating point mode in a struct or module scope by using a comptime block.

    See also:

    1. @setRuntimeSafety(safety_on: bool) void

    Sets whether runtime safety checks are enabled for the scope that contains the function call.

    test.zig

    1. test "@setRuntimeSafety" {
    2. // The builtin applies to the scope that it is called in. So here, integer overflow
    3. // will not be caught in ReleaseFast and ReleaseSmall modes:
    4. // var x: u8 = 255;
    5. // x += 1; // undefined behavior in ReleaseFast/ReleaseSmall modes.
    6. {
    7. // However this block has safety enabled, so safety checks happen here,
    8. // even in ReleaseFast and ReleaseSmall modes.
    9. @setRuntimeSafety(true);
    10. var x: u8 = 255;
    11. x += 1;
    12. {
    13. // The value can be overridden at any scope. So here integer overflow
    14. // would not be caught in any build mode.
    15. @setRuntimeSafety(false);
    16. // var x: u8 = 255;
    17. // x += 1; // undefined behavior in all build modes.
    18. }
    19. }
    20. }

    Shell

    1. $ zig test test.zig -OReleaseFast
    2. 1/1 test "@setRuntimeSafety"... thread 797125 panic: integer overflow
    3. error: the following test command crashed:
    4. docgen_tmp/zig-cache/o/7b3f38578dd3c68a8e61771c6005cfea/test /home/andy/Downloads/zig/build-release/zig

    Note: it is planned to replace @setRuntimeSafety with @optimizeFor

    @shlExact

    1. @shlExact(value: T, shift_amt: Log2T) T

    Performs the left shift operation (<<). For unsigned integers, the result is if any 1 bits are shifted out. For signed integers, the result is undefined if any bits that disagree with the resultant sign bit are shifted out.

    The type of shift_amt is an unsigned integer with log2(T.bit_count) bits. This is because shift_amt >= T.bit_count is undefined behavior.

    See also:

    @shlWithOverflow

    1. @shlWithOverflow(comptime T: type, a: T, shift_amt: Log2T, result: *T) bool

    Performs result.* = a << b. If overflow or underflow occurs, stores the overflowed bits in result and returns true. If no overflow or underflow occurs, returns false.

    The type of shift_amt is an unsigned integer with log2(T.bit_count) bits. This is because shift_amt >= T.bit_count is undefined behavior.

    See also:

    @shrExact

    1. @shrExact(value: T, shift_amt: Log2T) T

    Performs the right shift operation (>>). Caller guarantees that the shift will not shift any 1 bits out.

    The type of shift_amt is an unsigned integer with log2(T.bit_count) bits. This is because shift_amt >= T.bit_count is undefined behavior.

    See also:

    @shuffle

    1. @shuffle(comptime E: type, a: std.meta.Vector(a_len, E), b: std.meta.Vector(b_len, E), comptime mask: std.meta.Vector(mask_len, i32)) std.meta.Vector(mask_len, E)

    Constructs a new by selecting elements from a and b based on mask.

    Each element in mask selects an element from either a or b. Positive numbers select from a starting at 0. Negative values select from b, starting at -1 and going down. It is recommended to use the ~ operator from indexes from b so that both indexes can start from 0 (i.e. ~@as(i32, 0) is -1).

    For each element of mask, if it or the selected value from a or b is undefined, then the resulting element is undefined.

    a_len and b_len may differ in length. Out-of-bounds element indexes in mask result in compile errors.

    If a or b is undefined, it is equivalent to a vector of all undefined with the same length as the other vector. If both vectors are undefined, @shuffle returns a vector with all elements undefined.

    E must be an integer, , pointer, or bool. The mask may be any vector length, and its length determines the result length.

    vector_shuffle.zig

    1. const std = @import("std");
    2. const Vector = std.meta.Vector;
    3. const expect = std.testing.expect;
    4. test "vector @shuffle" {
    5. const a: Vector(7, u8) = [_]u8{ 'o', 'l', 'h', 'e', 'r', 'z', 'w' };
    6. const b: Vector(4, u8) = [_]u8{ 'w', 'd', '!', 'x' };
    7. // To shuffle within a single vector, pass undefined as the second argument.
    8. // Notice that we can re-order, duplicate, or omit elements of the input vector
    9. const mask1: Vector(5, i32) = [_]i32{ 2, 3, 1, 1, 0 };
    10. const res1: Vector(5, u8) = @shuffle(u8, a, undefined, mask1);
    11. try expect(std.mem.eql(u8, &@as([5]u8, res1), "hello"));
    12. // Combining two vectors
    13. const mask2: Vector(6, i32) = [_]i32{ -1, 0, 4, 1, -2, -3 };
    14. const res2: Vector(6, u8) = @shuffle(u8, a, b, mask2);
    15. try expect(std.mem.eql(u8, &@as([6]u8, res2), "world!"));
    16. }

    Shell

    1. $ zig test vector_shuffle.zig
    2. 1/1 test "vector @shuffle"... OK
    3. All 1 tests passed.

    See also:

    1. @sizeOf(comptime T: type) comptime_int

    This function returns the number of bytes it takes to store T in memory. The result is a target-specific compile time constant.

    This size may contain padding bytes. If there were two consecutive T in memory, this would be the offset in bytes between element at index 0 and the element at index 1. For integer, consider whether you want to use @sizeOf(T) or @typeInfo(T).Int.bits.

    This function measures the size at runtime. For types that are disallowed at runtime, such as comptime_int and type, the result is 0.

    See also:

    @splat

    1. @splat(comptime len: u32, scalar: anytype) std.meta.Vector(len, @TypeOf(scalar))

    Produces a vector of length len where each element is the value scalar:

    vector_splat.zig

    1. const std = @import("std");
    2. const expect = std.testing.expect;
    3. test "vector @splat" {
    4. const scalar: u32 = 5;
    5. const result = @splat(4, scalar);
    6. comptime try expect(@TypeOf(result) == std.meta.Vector(4, u32));
    7. try expect(std.mem.eql(u32, &@as([4]u32, result), &[_]u32{ 5, 5, 5, 5 }));
    8. }

    Shell

    1. $ zig test vector_splat.zig
    2. 1/1 test "vector @splat"... OK
    3. All 1 tests passed.

    scalar must be an , bool, , or pointer.

    See also:

    @reduce

    1. @reduce(comptime op: std.builtin.ReduceOp, value: anytype) std.meta.Child(value)

    Transforms a into a scalar value by performing a sequential horizontal reduction of its elements using the specified operator op.

    Not every operator is available for every vector element type:

    • .And, .Or, .Xor are available for bool vectors,
    • .Min, .Max, .Add, .Mul are available for floating point vectors,
    • Every operator is available for vectors.

    Note that .Add and .Mul reductions on integral types are wrapping; when applied on floating point types the operation associativity is preserved, unless the float mode is set to Optimized.

    vector_reduce.zig

    1. const std = @import("std");
    2. const expect = std.testing.expect;
    3. test "vector @reduce" {
    4. const value: std.meta.Vector(4, i32) = [_]i32{ 1, -1, 1, -1 };
    5. const result = value > @splat(4, @as(i32, 0));
    6. // result is { true, false, true, false };
    7. comptime try expect(@TypeOf(result) == std.meta.Vector(4, bool));
    8. const is_all_true = @reduce(.And, result);
    9. comptime try expect(@TypeOf(is_all_true) == bool);
    10. try expect(is_all_true == false);
    11. }

    Shell

    1. $ zig test vector_reduce.zig
    2. 1/1 test "vector @reduce"... OK
    3. All 1 tests passed.

    See also:

    1. @src() std.builtin.SourceLocation

    Returns a SourceLocation struct representing the function’s name and location in the source code. This must be called in a function.

    source_location.zig

    1. const std = @import("std");
    2. const expect = std.testing.expect;
    3. test "@src" {
    4. try doTheTest();
    5. }
    6. fn doTheTest() !void {
    7. const src = @src();
    8. try expect(src.line == 9);
    9. try expect(src.column == 17);
    10. try expect(std.mem.endsWith(u8, src.fn_name, "doTheTest"));
    11. try expect(std.mem.endsWith(u8, src.file, "source_location.zig"));
    12. }

    Shell

    1. $ zig test source_location.zig
    2. 1/1 test "@src"... OK
    3. All 1 tests passed.

    1. @sqrt(value: anytype) @TypeOf(value)

    Performs the square root of a floating point number. Uses a dedicated hardware instruction when available.

    Supports Floats and of floats, with the caveat that some float operations are not yet implemented for all float types.

    @sin

    1. @sin(value: anytype) @TypeOf(value)

    Sine trigonometric function on a floating point number. Uses a dedicated hardware instruction when available.

    Supports and Vectors of floats, with the caveat that .

    1. @cos(value: anytype) @TypeOf(value)

    Cosine trigonometric function on a floating point number. Uses a dedicated hardware instruction when available.

    Supports Floats and of floats, with the caveat that some float operations are not yet implemented for all float types.

    @exp

    1. @exp(value: anytype) @TypeOf(value)

    Base-e exponential function on a floating point number. Uses a dedicated hardware instruction when available.

    Supports and Vectors of floats, with the caveat that .

    1. @exp2(value: anytype) @TypeOf(value)

    Base-2 exponential function on a floating point number. Uses a dedicated hardware instruction when available.

    Supports Floats and of floats, with the caveat that some float operations are not yet implemented for all float types.

    @log

    1. @log(value: anytype) @TypeOf(value)

    Returns the natural logarithm of a floating point number. Uses a dedicated hardware instruction when available.

    Supports and Vectors of floats, with the caveat that .

    1. @log2(value: anytype) @TypeOf(value)

    Returns the logarithm to the base 2 of a floating point number. Uses a dedicated hardware instruction when available.

    Supports Floats and of floats, with the caveat that some float operations are not yet implemented for all float types.

    @log10

    1. @log10(value: anytype) @TypeOf(value)

    Returns the logarithm to the base 10 of a floating point number. Uses a dedicated hardware instruction when available.

    Supports and Vectors of floats, with the caveat that .

    1. @fabs(value: anytype) @TypeOf(value)

    Returns the absolute value of a floating point number. Uses a dedicated hardware instruction when available.

    Supports Floats and of floats, with the caveat that some float operations are not yet implemented for all float types.

    @floor

    1. @floor(value: anytype) @TypeOf(value)

    Returns the largest integral value not greater than the given floating point number. Uses a dedicated hardware instruction when available.

    Supports and Vectors of floats, with the caveat that .

    1. @ceil(value: anytype) @TypeOf(value)

    Returns the smallest integral value not less than the given floating point number. Uses a dedicated hardware instruction when available.

    Supports Floats and of floats, with the caveat that some float operations are not yet implemented for all float types.

    @trunc

    1. @trunc(value: anytype) @TypeOf(value)

    Rounds the given floating point number to an integer, towards zero. Uses a dedicated hardware instruction when available.

    Supports and Vectors of floats, with the caveat that .

    1. @round(value: anytype) @TypeOf(value)

    Rounds the given floating point number to an integer, away from zero. Uses a dedicated hardware instruction when available.

    Supports Floats and of floats, with the caveat that some float operations are not yet implemented for all float types.

    @subWithOverflow

    1. @subWithOverflow(comptime T: type, a: T, b: T, result: *T) bool

    Performs result.* = a - b. If overflow or underflow occurs, stores the overflowed bits in result and returns true. If no overflow or underflow occurs, returns false.

    @tagName

    1. @tagName(value: anytype) [:0]const u8

    Converts an enum value or union value to a string literal representing the name.

    If the enum is non-exhaustive and the tag value does not map to a name, it invokes safety-checked .

    1. @This() type

    Returns the innermost struct, enum, or union that this function call is inside. This can be useful for an anonymous struct that needs to refer to itself:

    this_innermost.zig

    1. const std = @import("std");
    2. const expect = std.testing.expect;
    3. test "@This()" {
    4. var items = [_]i32{ 1, 2, 3, 4 };
    5. const list = List(i32){ .items = items[0..] };
    6. try expect(list.length() == 4);
    7. }
    8. fn List(comptime T: type) type {
    9. return struct {
    10. const Self = @This();
    11. items: []T,
    12. fn length(self: Self) usize {
    13. return self.items.len;
    14. }
    15. };
    16. }

    Shell

    1. $ zig test this_innermost.zig
    2. 1/1 test "@This()"... OK
    3. All 1 tests passed.

    When @This() is used at file scope, it returns a reference to the struct that corresponds to the current file.

    1. @truncate(comptime T: type, integer: anytype) T

    This function truncates bits from an integer type, resulting in a smaller or same-sized integer type.

    The following produces safety-checked Undefined Behavior:

    test.zig

    1. test "integer cast panic" {
    2. var a: u16 = 0xabcd;
    3. var b: u8 = @intCast(u8, a);
    4. _ = b;
    5. }

    Shell

    1. $ zig test test.zig
    2. 1/1 test "integer cast panic"... thread 797343 panic: integer cast truncated bits
    3. /home/andy/Downloads/zig/docgen_tmp/test.zig:3:17: 0x207a05 in test "integer cast panic" (test)
    4. var b: u8 = @intCast(u8, a);
    5. ^
    6. /home/andy/Downloads/zig/lib/std/special/test_runner.zig:80:28: 0x22f413 in std.special.main (test)
    7. } else test_fn.func();
    8. ^
    9. /home/andy/Downloads/zig/lib/std/start.zig:543:22: 0x227e0c in std.start.callMain (test)
    10. root.main();
    11. ^
    12. /home/andy/Downloads/zig/lib/std/start.zig:495:12: 0x20922e in std.start.callMainWithArgs (test)
    13. return @call(.{ .modifier = .always_inline }, callMain, .{});
    14. ^
    15. /home/andy/Downloads/zig/lib/std/start.zig:409:17: 0x2082c6 in std.start.posixCallMainAndExit (test)
    16. std.os.exit(@call(.{ .modifier = .always_inline }, callMainWithArgs, .{ argc, argv, envp }));
    17. ^
    18. /home/andy/Downloads/zig/lib/std/start.zig:322:5: 0x2080d2 in std.start._start (test)
    19. @call(.{ .modifier = .never_inline }, posixCallMainAndExit, .{});
    20. ^
    21. error: the following test command crashed:
    22. docgen_tmp/zig-cache/o/8e4964e05ddaf866e77360a551b3c05b/test /home/andy/Downloads/zig/build-release/zig

    However this is well defined and working code:

    truncate.zig

    1. const std = @import("std");
    2. const expect = std.testing.expect;
    3. test "integer truncation" {
    4. var a: u16 = 0xabcd;
    5. var b: u8 = @truncate(u8, a);
    6. try expect(b == 0xcd);
    7. }

    Shell

    1. $ zig test truncate.zig
    2. 1/1 test "integer truncation"... OK
    3. All 1 tests passed.

    This function always truncates the significant bits of the integer, regardless of endianness on the target platform.

    @Type

    1. @Type(comptime info: std.builtin.TypeInfo) type

    This function is the inverse of . It reifies type information into a type.

    It is available for the following types:

    For these types, @Type is not available:

    @typeInfo

    1. @typeInfo(comptime T: type) std.builtin.TypeInfo

    Provides type reflection.

    For , unions, , and error sets, the fields are guaranteed to be in the same order as declared. For declarations, the order is unspecified.

    @typeName

    1. @typeName(T: type) *const [N:0]u8

    This function returns the string representation of a type, as an array. It is equivalent to a string literal of the type name.

    1. @TypeOf(...) type

    @TypeOf is a special builtin function that takes any (nonzero) number of expressions as parameters and returns the type of the result, using .

    The expressions are evaluated, however they are guaranteed to have no runtime side-effects:

    no_runtime_side_effects.zig

    1. const std = @import("std");
    2. const expect = std.testing.expect;
    3. test "no runtime side effects" {
    4. var data: i32 = 0;
    5. const T = @TypeOf(foo(i32, &data));
    6. comptime try expect(T == i32);
    7. try expect(data == 0);
    8. }
    9. fn foo(comptime T: type, ptr: *T) T {
    10. ptr.* += 1;
    11. return ptr.*;
    12. }

    Shell

      This is the same thing as union initialization syntax, except that the field name is a -known value rather than an identifier token.

      @unionInit forwards its result location to init_expr.