typestar

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

  1. __init__(out self, var cells: List[Int]) takes the list by ownership and moves it in with ^.
  2. __getitem__ reads a cell; __setitem__ needs mut self to write one.
  3. grid[1] = 20 then grid[1] exercise both halves.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 5 in Operators, step 13 of 22 in Structs & traits.

← Previous Next →