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
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
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 🙏
6 Replies
Ryulord
Ryulord2mo ago
I think you might just want a List[List[Int]]
Martin Dudek
Martin DudekOP2mo ago
This will copy the lists as far as i see:
fn main():
var m1 = List[Int](1,2)
var m2 = List[Int](3,4)
var l = List[List[Int]](m1,m2)
l[0][0] = 5
print(m1[0]) # -> 1
fn main():
var m1 = List[Int](1,2)
var m2 = List[Int](3,4)
var l = List[List[Int]](m1,m2)
l[0][0] = 5
print(m1[0]) # -> 1
Ryulord
Ryulord2mo ago
The Reference type is usable but still kinda a pain. Arc is also an option
Martin Dudek
Martin DudekOP2mo ago
It would be great if someone could post how to implement this example with References (and/or Arc) - never used them so not sure how to do it
sora
sora2mo ago
from memory import Arc

fn main():
l1 = Arc(List(1, 2))
l2 = Arc(List(3, 4))
l3 = List(l1, l2)
l3[0][][0] = 10
print(l1[].__str__())
from memory import Arc

fn main():
l1 = Arc(List(1, 2))
l2 = Arc(List(3, 4))
l3 = List(l1, l2)
l3[0][][0] = 10
print(l1[].__str__())
Martin Dudek
Martin DudekOP2mo ago
this looks great, thanks a lot
Want results from more Discord servers?
Add your server