Lesson contents

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
lesson.mojo
@fieldwise_init
struct Item:
    var units: Int
    var price: Int

def main() raises:
    var item = Item(2, 3)
    print(item.units * item.price)
Output
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
lesson.mojo
@fieldwise_init
struct Item:
    var units: Int
    var price: Int

def main() raises:
    var item = Item(4, 3)
    print(item.units * item.price)
Output
12
Run the example
Terminal
mojo lesson.mojo
Official documentation