M
Modular6mo ago
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[])
@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:
3 Replies
tcorpse
tcorpseOP6mo ago
if I change label to be an Int, it works fine
Frank Saez
Frank Saez6mo ago
I've tried this
@value
struct Test(Stringable):

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: Self):
self.label = label
self.prev = UnsafePointer[Test](prev)


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

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

fn main():

var x = Test("x")
var y = x.next("y")
var z = y.prev[]
print(x)
print(y)
print(z)
@value
struct Test(Stringable):

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: Self):
self.label = label
self.prev = UnsafePointer[Test](prev)


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

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

fn main():

var x = Test("x")
var y = x.next("y")
var z = y.prev[]
print(x)
print(y)
print(z)
and it gives me :
Test: x
Test: y
Test: x
Test: x
Test: y
Test: x
I guess the difference is in :
self.prev = UnsafePointer[Test](prev)
self.prev = UnsafePointer[Test](prev)
sora
sora5mo ago
I think you hit a bug of Mojo's ASAP destruction: x is deleted on the line var y = x.next("y") Try adding _ = x; _ = y to the end of your file
Want results from more Discord servers?
Add your server