liveBook · Manning

Type coercion

As explained in Systems Programming with Zig

Type coercion is the conversion of a value from one type to another so that an operation can accept it.

Type coercion converts a value from one type to another so an operation can accept it. In Zig, coercion must be unambiguous: numeric operations are especially restrictive about which types can be used together. The goal is to make conversions deliberate rather than allow surprising casts or unintended changes to data. section 1.3.1

Zig determines the type of every variable and expression during code analysis, often without an explicit annotation. But inferring a type is not the same as silently converting one: converting a boolean to an integer or an integer to a float must be declared explicitly, typically using a built-in function. section 2.1.1

Not every coercion needs an explicit conversion function. A mutable pointer can be coerced to a constant pointer: a *const i32 refers to an i32 that cannot be changed through that pointer. This is useful for a function that reads pointed-to data but does not need permission to mutate it. section 2.2.1

Listing 2.8 Coercing a constant pointer to a regular pointer
var x: i32 = 0;
const x_mutable_ptr = &x; #1
const x_const_ptr: *const i32 = x_mutable_ptr;  #2

The mutable pointer to x is assigned to a *const i32; the resulting pointer cannot be used to change the underlying value. section 2.2.1

How Systems Programming with Zig covers it

How deep it goes
Defines coercion restrictions and explains pointer constness, while deferring the built-in functions typically used for explicit conversions.
Examples
Contrasts boolean-to-integer and integer-to-float conversions with assigning a mutable pointer to a constant-pointer variable.
What you can do after
Evaluate whether a conversion needs to be explicit and recognize when a mutable pointer can serve as a constant pointer.
How it connects
Connects coercion with static typing, type inference, pointers, and mutability.

Also explained in

Compare how 2 books explain type coercion →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Systems Programming with Zig. The section links point to the parts of the book it draws on.