Card 1 / 11
Zig structs are value types — they live on the stack by default. Define a Point struct and write functions that operate on it.
const Point = struct {
x: i32,
y: i32,
};
const p = Point{ .x = 1, .y = 2 };Note: struct values are passed by value in Zig. To modify one, accept a pointer *Point.
Points below are written (x, y).
translate
p |
dx |
dy |
result |
|---|---|---|---|
(1, 2) |
3 |
-1 |
(4, 1) |
manhattanDistance
a |
b |
result |
|---|---|---|
(0, 0) |
(3, 4) |
7 |
(5, 5) |
(5, 5) |
0 |
Return a new Point with translated coordinates: Point{ .x = p.x + dx, .y = p.y + dy }.
/// Return a new point translated by (dx, dy)
fn translate(p: Point, dx: i32, dy: i32) Point {
return Point{ .x = p.x + dx, .y = p.y + dy };
}
/// Return the Manhattan distance between two points
fn manhattanDistance(a: Point, b: Point) u32 {
const dx = if (a.x > b.x) a.x - b.x else b.x - a.x;
const dy = if (a.y > b.y) a.y - b.y else b.y - a.y;
return @intCast(dx + dy);
}Card 2 / 11
Define methods on a struct. In Zig, methods are just functions declared inside a struct with self as the first parameter: