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
Ring[size: Int]declares the parameter in the struct header.- Inside the body it is always written
Self.size; baresizeis an error. Ring[4]()stamps out a four-slot ring, andputwraps the index with%.
Keywords and builtins used here
CopyableIntListMovabledefformainprintputrangereturnroomselfstructvar
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.
Step 3 of 5 in Compile-time Mojo, step 3 of 22 in Parameters & SIMD.