Why would zig accept a u128 value to be assigned to a u32 type ?
Why would below code work ?
const std = @import("std");
const x: u32 = @as(u128, 10); // I'm converting to u128 but x is type u32
pub fn main() !void {
std.debug.print("{d}\n", .{x});
}
Because the compiler sees that 10 fits into u32
. From the documentation:
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.
For example, this doesn't compile:
const x: u32 = @as(u128, 2199023255552);
// error: type 'u32' cannot represent integer value '2199023255552'