M
Modular13mo ago
benny

Any ideas on implementing linked based structs in mojo?

I’m working on data structures in mojo and hit a roadblock at objects like linked lists and trees, how would I code a pointer to another object of the same type in mojo? and is there a way to use DTypePointers to ensure the result is string able?
1 Reply
benny
bennyOP13mo ago
@value
struct Node[T: DType]:
var value: SIMD[T, 1]
var nxt: Pointer[Node[T]]

fn __getitem__(self, i: Int) -> SIMD[T, 1]:
return self.value

fn __setitem__(inout self, i: Int, x: SIMD[T, 1]):
self.value = x

fn _set_next(inout self, owned nxt: Node[T]):
self.nxt = Pointer[Node[T]].address_of(nxt)

fn _get_next(self) -> Node[T]:
...
@value
struct Node[T: DType]:
var value: SIMD[T, 1]
var nxt: Pointer[Node[T]]

fn __getitem__(self, i: Int) -> SIMD[T, 1]:
return self.value

fn __setitem__(inout self, i: Int, x: SIMD[T, 1]):
self.value = x

fn _set_next(inout self, owned nxt: Node[T]):
self.nxt = Pointer[Node[T]].address_of(nxt)

fn _get_next(self) -> Node[T]:
...
The above code works, just have no idea how to implement _get_next
@value
@register_passable
struct Node[T: DType]:
var value: SIMD[T, 1]
var next: Pointer[Node[T]]
@value
@register_passable
struct Node[T: DType]:
var value: SIMD[T, 1]
var next: Pointer[Node[T]]
The above code seems to be the correct answer, but throws errors when run, very complicated system errors, any ideas? I think the issue is with DType != Register passable, but how can you cast register passable types to printable values?
Want results from more Discord servers?
Add your server