ModularM
Modular2y ago
5 replies
tcorpse

UnsafePointer & Structs

would anyone be able to help me understand what is happening here? why are the outputs of the two print statements different?
@value
struct Test:
    
    var prev: UnsafePointer[Test]
    var label: String

    fn __init__(inout self, label: String):
        self.label = label
        self.prev = UnsafePointer[Test]()

    fn __init__(inout self, label: String, prev: Test):
        self.label = label
        self.prev = UnsafePointer[Test].address_of(prev)

    fn __str__(self) -> String:
        return "Test: " + self.label

    fn next(self, label: String) -> Test:
        return Test(label, self)

fn main():

    var x = Test("x")

    print(x.next("y").prev[])
    var y = x.next("y")
    print(y.prev[])


The output is:
Test: x
Test:
Was this page helpful?