tcorpse
tcorpse
MModular
Created by tcorpse on 7/4/2024 in #questions
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[])
@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:
Test: x
Test:
6 replies