ModularM
Modular13mo ago
40 replies
Deftioon

Is there a way to reflect changes to a variable in the reference?

Here's a small reproducible example:
struct MyList:
    var list: List[Int]
    
    fn __init__(out self):
        self.list = List[Int]()
    
    fn __getitem__(self, index: Int) -> ref[self.list] Int:
        return self.list[index]
    
    fn append(mut self, value: Int) -> None:
        self.list.append(value)
    
    fn do_stuff(mut self, index: Int) -> None:
        self.list[index] = 1

fn main() raises -> None:
    var mylist = MyList()
    mylist.append(0)
    var q1 = mylist[0]
    print(q1)
    mylist.do_stuff(0)
    print(q1)
    print(mylist[0])

This outputs:
0
0
1

When I want it to output
0
1
1

My logic was that because q1 is a reference to mylist.list , whenever I change mylist.list, it should also be reflected in q1. But it seems q1 is copying the value instead of taking a reference? Am I misunderstanding how references work as a whole?
Was this page helpful?