-
Book Overview & Buying
-
Table Of Contents
Learning Zig
By :
In a world where data doesn’t always appear in the shape you need, casting is the art of politely (or sometimes forcefully) reshaping one type into another. Zig provides a strong distinction between safe, automatic conversions (coercions) and those that require a deliberate cast (explicit casts). This reduces surprises, making it harder for accidental transformations to slip under the radar and cause subtle bugs.
Coercion happens automatically when Zig can guarantee a safe and unambiguous conversion. For example, assigning a u8 to a u16 is safe—no information is lost because a u16 can hold every value a u8 can:
const a: u8 = 42;
const b: u16 = a; // Automatically widens from u8 to u16
These aren’t “casts” in the traditional sense. No special syntax is needed. The compiler knows what you want and ensures it’s harmless. Coercions can...