typestar

Parametric structs in Mojo

A struct parameter fixes a size at compile time, so no capacity check survives.

struct Ring[size: Int](Copyable, Movable):
    var slots: List[Int]

    def __init__(out self):
        self.slots = List[Int](capacity=Self.size)
        for _ in range(Self.size):
            self.slots.append(0)

    def put(mut self, index: Int, value: Int):
        self.slots[index % Self.size] = value

    def room(self) -> Int:
        return Self.size


def main():
    var ring = Ring[4]()
    ring.put(6, 99)
    print(ring.room(), ring.slots[2])

How it works

  1. Ring[size: Int] declares the parameter in the struct header.
  2. Inside the body it is always written Self.size; bare size is an error.
  3. Ring[4]() stamps out a four-slot ring, and put wraps the index with %.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
387
Tokens
124
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 106 seconds.

Type this snippet

Step 3 of 5 in Compile-time Mojo, step 3 of 22 in Parameters & SIMD.

← Previous Next →