M
Modular16mo ago
Danny Go

Pointer to a custom struct?

Is it possible to create pointers to a custom struct instance, and be able to load the instance from the pointer? According to the AI bot, "Mojo's Pointer struct is designed to work with basic types like Int, and it's not clear if it can directly handle custom structs". Here is my latest attempt (a linked list):
@register_passable("trivial")
struct ListNode:
var val: Int
var next: Pointer[ListNode]

@always_inline
fn __init__(val: Int) -> Self:
return ListNode {val: val, next: Pointer[ListNode].get_null()}

let node1 = ListNode(1)
@register_passable("trivial")
struct ListNode:
var val: Int
var next: Pointer[ListNode]

@always_inline
fn __init__(val: Int) -> Self:
return ListNode {val: val, next: Pointer[ListNode].get_null()}

let node1 = ListNode(1)
Which got an error:
error: Expression [91]:33:25: LLVM Translation failed for operation: builtin.unrealized_conversion_cast
return ListNode {val: val, next: Pointer[ListNode].get_null()}
^
error: Expression [91]:33:25: LLVM Translation failed for operation: builtin.unrealized_conversion_cast
return ListNode {val: val, next: Pointer[ListNode].get_null()}
^
3 Replies
Danny Go
Danny GoOP16mo ago
The problem here seem to be the use of Pointer[ListNode]. The code will work if it's Pointer[Int] Any idea how to make the linked list work? Thanks
Helehex
Helehex16mo ago
This compiles, but im not sure if it works
struct ListNode:
var val: Int
var next: Pointer[ListNode]

@always_inline
fn __init__(inout self, val: Int):
self.val = val
self.next = Pointer[ListNode].get_null()

let node1 = ListNode(1)
struct ListNode:
var val: Int
var next: Pointer[ListNode]

@always_inline
fn __init__(inout self, val: Int):
self.val = val
self.next = Pointer[ListNode].get_null()

let node1 = ListNode(1)
i believe things marked with @register_passable aren't allowed to have dynamic memory and allocate to heap im not sure, here from the docs: " 1. @register_passable types are not able to hold instances of types that are not themselves @register_passable. 2. Instances of @register_passable types do not have predictable identity, and so the self pointer is not stable/predictable (e.g. in hash tables). 3. @register_passable arguments and result are exposed to C and C++ directly, instead of being passed by-pointer. 4. The init and copyinit methods of this type are implicitly static (like new in Python) and returns its result by-value instead of taking inout self. "
Moosems / Three chickens
Try using
@value
@reguster_passable(“trivial”)
@value
@reguster_passable(“trivial”)
I can’t test this right now but will probably try this later.
Want results from more Discord servers?
Add your server