Subscripting a struct in Mojo
__getitem__ and __setitem__ put square-bracket syntax on your own container.
struct Grid(Movable):
var cells: List[Int]
def __init__(out self, var cells: List[Int]):
self.cells = cells^
def __getitem__(self, i: Int) -> Int:
return self.cells[i]
def __setitem__(mut self, i: Int, value: Int):
self.cells[i] = value
def main():
var grid = Grid([1, 2, 3])
grid[1] = 20
print(grid[0], grid[1], grid[2])
How it works
__init__(out self, var cells: List[Int])takes the list by ownership and moves it in with^.__getitem__reads a cell;__setitem__needsmut selfto write one.grid[1] = 20thengrid[1]exercise both halves.
Keywords and builtins used here
IntListMovabledefmainprintreturnselfstructvar
The run, in numbers
- Lines
- 17
- Characters to type
- 326
- Tokens
- 107
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 86 seconds.
Step 3 of 5 in Operators, step 13 of 22 in Structs & traits.