Casting

    Type coercion occurs when one type is expected, but different type is provided:

    type_coercion.zig

    Shell

    1. 1/3 test "type coercion - variable declaration"... OK
    2. 2/3 test "type coercion - function call"... OK
    3. 3/3 test "type coercion - @as builtin"... OK
    4. All 3 tests passed.

    Type coercions are only allowed when it is completely unambiguous how to get from one type to another, and the transformation is guaranteed to be safe. There is one exception, which is .

    Values which have the same representation at runtime can be cast to increase the strictness of the qualifiers, no matter how nested the qualifiers are:

    • const - non-const to const is allowed
    • volatile - non-volatile to volatile is allowed
    • align - bigger to smaller alignment is allowed
    • error sets to supersets is allowed

    These casts are no-ops at runtime since the value representation does not change.

    no_op_casts.zig

    1. test "type coercion - const qualification" {
    2. var a: i32 = 1;
    3. var b: *i32 = &a;
    4. foo(b);
    5. }
    6. fn foo(_: *const i32) void {}

    Shell

    1. $ zig test no_op_casts.zig
    2. 1/1 test "type coercion - const qualification"... OK
    3. All 1 tests passed.

    In addition, pointers coerce to const optional pointers:

    pointer_coerce_const_optional.zig

    1. const std = @import("std");
    2. const expect = std.testing.expect;
    3. const mem = std.mem;
    4. test "cast *[1][*]const u8 to [*]const ?[*]const u8" {
    5. const window_name = [1][*]const u8{"window name"};
    6. const x: [*]const ?[*]const u8 = &window_name;
    7. try expect(mem.eql(u8, std.mem.sliceTo(@ptrCast([*:0]const u8, x[0].?), 0), "window name"));
    8. }

    Shell

    1. $ zig test pointer_coerce_const_optional.zig
    2. 1/1 test "cast *[1][*]const u8 to [*]const ?[*]const u8"... OK
    3. All 1 tests passed.

    Type Coercion: Integer and Float Widening

    coerce to integer types which can represent every value of the old type, and likewise Floats coerce to float types which can represent every value of the old type.

    test_integer_widening.zig

    1. const std = @import("std");
    2. const builtin = @import("builtin");
    3. const expect = std.testing.expect;
    4. const mem = std.mem;
    5. test "integer widening" {
    6. var a: u8 = 250;
    7. var b: u16 = a;
    8. var c: u32 = b;
    9. var d: u64 = c;
    10. var e: u64 = d;
    11. var f: u128 = e;
    12. try expect(f == a);
    13. }
    14. test "implicit unsigned integer to signed integer" {
    15. var a: u8 = 250;
    16. var b: i16 = a;
    17. try expect(b == 250);
    18. }
    19. test "float widening" {
    20. // Note: there is an open issue preventing this from working on aarch64:
    21. // https://github.com/ziglang/zig/issues/3282
    22. if (builtin.target.cpu.arch == .aarch64) return error.SkipZigTest;
    23. var a: f16 = 12.34;
    24. var b: f32 = a;
    25. var c: f64 = b;
    26. var d: f128 = c;
    27. try expect(d == a);
    28. }

    Shell

    1. $ zig test test_integer_widening.zig
    2. 1/3 test "integer widening"... OK
    3. 2/3 test "implicit unsigned integer to signed integer"... OK
    4. 3/3 test "float widening"... OK
    5. All 3 tests passed.

    Type Coercion: Coercion Float to Int

    A compiler error is appropriate because this ambiguous expression leaves the compiler two choices about the coercion.

    • Cast 54.0 to comptime_int resulting in @as(comptime_int, 10), which is casted to @as(f32, 10)
    • Cast 5 to comptime_float resulting in @as(comptime_float, 10.8), which is casted to @as(f32, 10.8)

    Shell

    1. $ zig test test.zig
    2. ./docgen_tmp/test.zig:3:18: error: float value 54.000000 cannot be coerced to type 'comptime_int'
    3. var f: f32 = 54.0 / 5;
    4. ^
    5. ./docgen_tmp/test.zig:3:23: note: referenced here
    6. var f: f32 = 54.0 / 5;

    coerce__slices_arrays_and_ptrs.zig

    1. const std = @import("std");
    2. // You can assign constant pointers to arrays to a slice with
    3. // const modifier on the element type. Useful in particular for
    4. // String literals.
    5. test "*const [N]T to []const T" {
    6. var x1: []const u8 = "hello";
    7. var x2: []const u8 = &[5]u8{ 'h', 'e', 'l', 'l', 111 };
    8. try expect(std.mem.eql(u8, x1, x2));
    9. var y: []const f32 = &[2]f32{ 1.2, 3.4 };
    10. try expect(y[0] == 1.2);
    11. }
    12. // Likewise, it works when the destination type is an error union.
    13. test "*const [N]T to E![]const T" {
    14. var x1: anyerror![]const u8 = "hello";
    15. var x2: anyerror![]const u8 = &[5]u8{ 'h', 'e', 'l', 'l', 111 };
    16. try expect(std.mem.eql(u8, try x1, try x2));
    17. var y: anyerror![]const f32 = &[2]f32{ 1.2, 3.4 };
    18. try expect((try y)[0] == 1.2);
    19. }
    20. // Likewise, it works when the destination type is an optional.
    21. test "*const [N]T to ?[]const T" {
    22. var x1: ?[]const u8 = "hello";
    23. var x2: ?[]const u8 = &[5]u8{ 'h', 'e', 'l', 'l', 111 };
    24. try expect(std.mem.eql(u8, x1.?, x2.?));
    25. var y: ?[]const f32 = &[2]f32{ 1.2, 3.4 };
    26. try expect(y.?[0] == 1.2);
    27. }
    28. // In this cast, the array length becomes the slice length.
    29. test "*[N]T to []T" {
    30. var buf: [5]u8 = "hello".*;
    31. const x: []u8 = &buf;
    32. try expect(std.mem.eql(u8, x, "hello"));
    33. const buf2 = [2]f32{ 1.2, 3.4 };
    34. const x2: []const f32 = &buf2;
    35. try expect(std.mem.eql(f32, x2, &[2]f32{ 1.2, 3.4 }));
    36. }
    37. // Single-item pointers to arrays can be coerced to many-item pointers.
    38. test "*[N]T to [*]T" {
    39. var buf: [5]u8 = "hello".*;
    40. const x: [*]u8 = &buf;
    41. try expect(x[4] == 'o');
    42. // x[5] would be an uncaught out of bounds pointer dereference!
    43. }
    44. // Likewise, it works when the destination type is an optional.
    45. test "*[N]T to ?[*]T" {
    46. var buf: [5]u8 = "hello".*;
    47. const x: ?[*]u8 = &buf;
    48. try expect(x.?[4] == 'o');
    49. }
    50. // Single-item pointers can be cast to len-1 single-item arrays.
    51. test "*T to *[1]T" {
    52. var x: i32 = 1234;
    53. const y: *[1]i32 = &x;
    54. const z: [*]i32 = y;
    55. try expect(z[0] == 1234);
    56. }

    Shell

    1. $ zig test coerce__slices_arrays_and_ptrs.zig
    2. 1/7 test "*const [N]T to []const T"... OK
    3. 2/7 test "*const [N]T to E![]const T"... OK
    4. 3/7 test "*const [N]T to ?[]const T"... OK
    5. 4/7 test "*[N]T to []T"... OK
    6. 5/7 test "*[N]T to [*]T"... OK
    7. 6/7 test "*[N]T to ?[*]T"... OK
    8. 7/7 test "*T to *[1]T"... OK
    9. All 7 tests passed.

    See also:

    The payload type of Optionals, as well as , coerce to the optional type.

    test_coerce_optionals.zig

    1. const std = @import("std");
    2. const expect = std.testing.expect;
    3. const x: ?i32 = 1234;
    4. const y: ?i32 = null;
    5. try expect(x.? == 1234);
    6. try expect(y == null);
    7. }

    Shell

    1. $ zig test test_coerce_optionals.zig
    2. 1/1 test "coerce to optionals"... OK
    3. All 1 tests passed.

    It works nested inside the Error Union Type, too:

    test_coerce_optional_wrapped_error_union.zig

    1. const std = @import("std");
    2. const expect = std.testing.expect;
    3. test "coerce to optionals wrapped in error union" {
    4. const x: anyerror!?i32 = 1234;
    5. const y: anyerror!?i32 = null;
    6. try expect((try x).? == 1234);
    7. try expect((try y) == null);
    8. }

    Shell

    1. $ zig test test_coerce_optional_wrapped_error_union.zig
    2. 1/1 test "coerce to optionals wrapped in error union"... OK
    3. All 1 tests passed.

    Type Coercion: Error Unions

    The payload type of an as well as the Error Set Type coerce to the error union type:

    test_coerce_to_error_union.zig

    Shell

    1. $ zig test test_coerce_to_error_union.zig
    2. 1/1 test "coercion to error unions"... OK
    3. All 1 tests passed.

    When a number is -known to be representable in the destination type, it may be coerced:

    test_coerce_large_to_small.zig

    1. const std = @import("std");
    2. const expect = std.testing.expect;
    3. test "coercing large integer type to smaller one when value is comptime known to fit" {
    4. const x: u64 = 255;
    5. const y: u8 = x;
    6. try expect(y == 255);
    7. }
    1. $ zig test test_coerce_large_to_small.zig
    2. 1/1 test "coercing large integer type to smaller one when value is comptime known to fit"... OK
    3. All 1 tests passed.

    Tagged unions can be coerced to enums, and enums can be coerced to tagged unions when they are comptime-known to be a field of the union that has only one possible value, such as :

    test_coerce_unions_enums.zig

    1. const std = @import("std");
    2. const expect = std.testing.expect;
    3. const E = enum {
    4. one,
    5. two,
    6. three,
    7. };
    8. const U = union(E) {
    9. one: i32,
    10. two: f32,
    11. three,
    12. };
    13. test "coercion between unions and enums" {
    14. var u = U{ .two = 12.34 };
    15. var e: E = u;
    16. try expect(e == E.two);
    17. const three = E.three;
    18. var another_u: U = three;
    19. try expect(another_u == E.three);
    20. }

    Shell

    1. $ zig test test_coerce_unions_enums.zig
    2. 1/1 test "coercion between unions and enums"... OK
    3. All 1 tests passed.

    See also:

    Zero Bit Types may be coerced to single-item , regardless of const.

    TODO document the reasoning for this

    TODO document whether vice versa should work and why

    coerce_zero_bit_types.zig

    1. test "coercion of zero bit types" {
    2. var x: void = {};
    3. var y: *void = x;
    4. _ = y;
    5. }

    Shell

    1. $ zig test coerce_zero_bit_types.zig
    2. 1/1 test "coercion of zero bit types"... OK
    3. All 1 tests passed.

    undefined can be cast to any type.

    Explicit casts are performed via . Some explicit casts are safe; some are not. Some explicit casts perform language-level assertions; some do not. Some explicit casts are no-ops at runtime; some are not.

    • @bitCast - change type but maintain bit representation
    • - make a pointer have more alignment
    • @boolToInt - convert true to 1 and false to 0
    • - obtain the integer tag value of an enum or tagged union
    • @errSetCast - convert to a smaller error set
    • - obtain the integer value of an error code
    • @floatCast - convert a larger float to a smaller float
    • - obtain the integer part of a float value
    • @intCast - convert between integer types
    • - obtain an enum value based on its integer tag value
    • @intToError - obtain an error code based on its integer value
    • - convert an integer to a float value
    • @intToPtr - convert an address to a pointer
    • - convert between pointer types
    • @ptrToInt - obtain the address of a pointer
    • - convert between integer types, chopping off bits

    Peer Type Resolution occurs in these places:

    This kind of type resolution chooses a type that all peer types can coerce into. Here are some examples:

    peer_type_resolution.zig

    Shell

    1. $ zig test peer_type_resolution.zig
    2. 1/7 test "peer resolve int widening"... OK
    3. 2/7 test "peer resolve arrays of different size to const slice"... OK
    4. 3/7 test "peer resolve array and const slice"... OK
    5. 4/7 test "peer type resolution: ?T and T"... OK
    6. 5/7 test "peer type resolution: *[0]u8 and []const u8"... OK
    7. 6/7 test "peer type resolution: *[0]u8, []const u8, and anyerror![]u8"... OK
    8. 7/7 test "peer type resolution: *const T and ?*T"... OK