Modeling data
Keep the quantity and unit price together in one record. Give the two fields names so you can tell what each number means.
Simple example
Multiply two fields.
Start2 × 3
Result6
const std = @import("std");
const Item = struct { units: i64, price: i64 };
pub fn main() !void {
const item = Item{ .units = 2, .price = 3 };
std.debug.print("{any}\n", .{item.units * item.price});
}
6
Advertisements
Everyday examples
A receipt lists four notebooks at three coins each. What is the cost of this line on the receipt?
Start4 notebooks × 3
Result12
const std = @import("std");
const Item = struct { units: i64, price: i64 };
pub fn main() !void {
const item = Item{ .units = 4, .price = 3 };
std.debug.print("{any}\n", .{item.units * item.price});
}
12