ModularM
Modular16mo ago
7 replies
Martin Dudek

List of references in Mojo

I'm a bit out of the loop with the latest Mojo developments, so I could use some guidance.

In Python, creating a list of references is simple:
m1 = [1, 2]
m2 = [3, 4]
l = [m1, m2]
l[0][0] = 5
print(m1[0])  # -> 5

How would we achieve similar functionality in Mojo nowadays?

Is UnsafePointer still the way to go, something like:
from memory import UnsafePointer
fn main():
    var m1 = UnsafePointer[Int].alloc(2)
    var m2 = UnsafePointer[Int].alloc(2)

    m1[0] = 1
    m1[1] = 2
    m2[0] = 3
    m2[1] = 4

    var l = List[UnsafePointer[Int]](capacity=2)
    l.append(m1)
    l.append(m2)

    l[0][0] = 5
    print(m1[0]) # -> 5


Or is there now a more elegant/safer way to achieve this using References?

Thx 🙏
Was this page helpful?