← All examples

Ptr cast

A pointer seen as pointing at another type: ptr.cast[T]['p'] keeps the address and whether it may write, and changes only what it claims to point at.

ptr_cast.zg
# A pointer seen as pointing at another type (owner, 2026-09-30: a): `ptr.cast[T]['p']` keeps the
# address and whether it may write, and changes only what it claims to point at. Always no_check.
extern.C fn malloc ['bytes': uint64] -> ptr.mut[uint8];
extern.C fn free ['p': ptr.mut[uint8]];

layout.C struct Point {
    x: int32,
    y: int32
}

MAIN {
    no_check let 'raw' := malloc[size.of[Point]];
    no_check let 'p' := ptr.cast[Point]['raw'];
    no_check ptr.write['p', value Point[x = 3, y = 4]];
    no_check let 'q' := ptr.read['p'];
    std::print.stored['q'.x, " ", 'q'.y, newln];
    no_check free['raw'];
}
Output
3 4