Casting
An implicit cast occurs when one type is expected, but different type is provided:
test.zig
Test 1/3 implicit cast - variable declaration...OK
Test 2/3 implicit cast - function call...OK
Test 3/3 implicit cast - invoke a type as a function...OK
All tests passed.
Implicit casts 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 C Pointers.
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 allowedvolatile
- non-volatile to volatile is allowedalign
- bigger to smaller alignment is allowed- to supersets is allowed
These casts are no-ops at runtime since the value representation does not change.
test.zig
test "implicit cast - const qualification" {
var a: i32 = 1;
var b: *i32 = &a;
foo(b);
}
fn foo(a: *const i32) void {}
$ zig test test.zig
Test 1/1 implicit cast - const qualification...OK
All tests passed.
In addition, pointers implicitly cast to const optional pointers:
test.zig
const std = @import("std");
const assert = std.debug.assert;
const mem = std.mem;
test "cast *[1][*]const u8 to [*]const ?[*]const u8" {
const window_name = [1][*]const u8{c"window name"};
const x: [*]const ?[*]const u8 = &window_name;
assert(mem.eql(u8, std.cstr.toSliceConst(x[0].?), "window name"));
}
$ zig test test.zig
Test 1/1 cast *[1][*]const u8 to [*]const ?[*]const u8...OK
All tests passed.
Implicit Cast: Integer and Float Widening
implicitly cast to integer types which can represent every value of the old type, and likewise Floats implicitly cast to float types which can represent every value of the old type.
test.zig
const std = @import("std");
const assert = std.debug.assert;
const mem = std.mem;
test "integer widening" {
var a: u8 = 250;
var b: u16 = a;
var c: u32 = b;
var d: u64 = c;
var e: u64 = d;
var f: u128 = e;
assert(f == a);
}
test "implicit unsigned integer to signed integer" {
var a: u8 = 250;
var b: i16 = a;
assert(b == 250);
}
test "float widening" {
var a: f16 = 12.34;
var b: f32 = a;
var c: f64 = b;
var d: f128 = c;
assert(d == a);
}
$ zig test test.zig
Test 1/3 integer widening...OK
Test 2/3 implicit unsigned integer to signed integer...OK
Test 3/3 float widening...OK
All tests passed.
Implicit Cast: Arrays and Pointers
$ zig test test.zig
Test 1/7 [N]T to []const T...OK
Test 2/7 [N]T to E![]const T...OK
Test 3/7 [N]T to ?[]const T...OK
Test 4/7 *[N]T to []T...OK
Test 5/7 *[N]T to [*]T...OK
Test 6/7 *[N]T to ?[*]T...OK
Test 7/7 *T to *[1]T...OK
All tests passed.
See also:
The payload type of , as well as null, implicitly cast to the optional type.
test.zig
const std = @import("std");
const assert = std.debug.assert;
test "implicit casting to optionals" {
const x: ?i32 = 1234;
const y: ?i32 = null;
assert(x.? == 1234);
assert(y == null);
}
Test 1/1 implicit casting to optionals...OK
It works nested inside the , too:
test.zig
const std = @import("std");
const assert = std.debug.assert;
test "implicit casting to optionals wrapped in error union" {
const x: anyerror!?i32 = 1234;
const y: anyerror!?i32 = null;
assert((try x).? == 1234);
assert((try y) == null);
}
$ zig test test.zig
Test 1/1 implicit casting to optionals wrapped in error union...OK
All tests passed.
Implicit Cast: Error Unions
The the payload type of an as well as the Error Set Type implicitly cast to the error union type:
test.zig
const std = @import("std");
const assert = std.debug.assert;
test "implicit casting to error unions" {
const x: anyerror!i32 = 1234;
const y: anyerror!i32 = error.Failure;
assert((try x) == 1234);
std.testing.expectError(error.Failure, y);
}
$ zig test test.zig
Test 1/1 implicit casting to error unions...OK
All tests passed.
Implicit Cast: Compile-Time Known Numbers
When a number is comptime-known to be representable in the destination type, it may be implicitly casted:
test.zig
$ zig test test.zig
Test 1/1 implicit casting large integer type to smaller one when value is comptime known to fit...OK
All tests passed.
Tagged unions can be implicitly cast to enums, and enums can be implicitly casted to tagged unions when they are -known to be a field of the union that has only one possible value, such as void:
const std = @import("std");
const assert = std.debug.assert;
const E = enum {
One,
Two,
Three,
};
const U = union(E) {
One: i32,
Two: f32,
Three,
};
test "implicit casting between unions and enums" {
var u = U{ .Two = 12.34 };
var e: E = u;
assert(e == E.Two);
const three = E.Three;
var another_u: U = three;
assert(another_u == E.Three);
}
$ zig test test.zig
Test 1/1 implicit casting between unions and enums...OK
All tests passed.
See also:
Implicit Cast: Zero Bit Types
Zero Bit Types may be implicitly casted to single-item , regardless of const.
TODO document the reasoning for this
TODO document whether vice versa should work and why
test.zig
test "implicit casting of zero bit types" {
var x: void = {};
var y: *void = x;
//var z: void = y; // TODO
}
$ zig test test.zig
Test 1/1 implicit casting of zero bit types...OK
All tests passed.
Implicit Cast: undefined
can be cast to any type.
Explicit casts are performed via Builtin Functions. 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.
- - change type but maintain bit representation
- @alignCast - make a pointer have more alignment
- - convert true to 1 and false to 0
- @bytesToSlice - convert a slice of bytes to a slice of another type
- - 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 a slice of anything to a slice of bytes
- @truncate - 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 implicitly cast into. Here are some examples:
test.zig
const std = @import("std");
const assert = std.debug.assert;
const mem = std.mem;
test "peer resolve int widening" {
var a: i8 = 12;
var b: i16 = 34;
var c = a + b;
assert(c == 46);
assert(@typeOf(c) == i16);
}
test "peer resolve arrays of different size to const slice" {
assert(mem.eql(u8, boolToStr(true), "true"));
assert(mem.eql(u8, boolToStr(false), "false"));
comptime assert(mem.eql(u8, boolToStr(true), "true"));
comptime assert(mem.eql(u8, boolToStr(false), "false"));
}
return if (b) "true" else "false";
}
test "peer resolve array and const slice" {
testPeerResolveArrayConstSlice(true);
comptime testPeerResolveArrayConstSlice(true);
}
fn testPeerResolveArrayConstSlice(b: bool) void {
const value1 = if (b) "aoeu" else ([]const u8)("zz");
const value2 = if (b) ([]const u8)("zz") else "aoeu";
assert(mem.eql(u8, value1, "aoeu"));
assert(mem.eql(u8, value2, "zz"));
}
test "peer type resolution: ?T and T" {
assert(peerTypeTAndOptionalT(true, false).? == 0);
assert(peerTypeTAndOptionalT(false, false).? == 3);
comptime {
assert(peerTypeTAndOptionalT(true, false).? == 0);
assert(peerTypeTAndOptionalT(false, false).? == 3);
}
}
fn peerTypeTAndOptionalT(c: bool, b: bool) ?usize {
if (c) {
return if (b) null else usize(0);
}
return usize(3);
}
test "peer type resolution: [0]u8 and []const u8" {
assert(peerTypeEmptyArrayAndSlice(true, "hi").len == 0);
assert(peerTypeEmptyArrayAndSlice(false, "hi").len == 1);
comptime {
assert(peerTypeEmptyArrayAndSlice(true, "hi").len == 0);
assert(peerTypeEmptyArrayAndSlice(false, "hi").len == 1);
}
}
fn peerTypeEmptyArrayAndSlice(a: bool, slice: []const u8) []const u8 {
if (a) {
return []const u8{};
}
return slice[0..1];
}
test "peer type resolution: [0]u8, []const u8, and anyerror![]u8" {
{
var data = "hi";
const slice = data[0..];
assert((try peerTypeEmptyArrayAndSliceAndError(true, slice)).len == 0);
assert((try peerTypeEmptyArrayAndSliceAndError(false, slice)).len == 1);
}
comptime {
var data = "hi";
const slice = data[0..];
assert((try peerTypeEmptyArrayAndSliceAndError(true, slice)).len == 0);
assert((try peerTypeEmptyArrayAndSliceAndError(false, slice)).len == 1);
}
}
fn peerTypeEmptyArrayAndSliceAndError(a: bool, slice: []u8) anyerror![]u8 {
if (a) {
return []u8{};
}
return slice[0..1];
}
test "peer type resolution: *const T and ?*T" {
const a = @intToPtr(*const usize, 0x123456789);
const b = @intToPtr(?*usize, 0x123456789);
assert(a == b);
assert(b == a);
}
$ zig test test.zig
Test 1/7 peer resolve int widening...OK
Test 2/7 peer resolve arrays of different size to const slice...OK
Test 3/7 peer resolve array and const slice...OK
Test 4/7 peer type resolution: ?T and T...OK
Test 5/7 peer type resolution: [0]u8 and []const u8...OK
Test 6/7 peer type resolution: [0]u8, []const u8, and anyerror![]u8...OK
All tests passed.