Struct with optional self type member crashes

I have the following mojo code - it just crashes!


fn main():
    _e = Employee("me", None)

@value
struct Employee:
    var name: String
    var assistant: Optional[Employee]

How can I achieve what I am looking for?

mojo version: mojo 25.3.0.dev2025042905 (b3907eb3)

Please file a bug. This should be a compiler error instead of a crash.

The reason you can’t do this is because the type has infinite size. Unlike in Python, Optional[Employee] is a single allocation, which contains an Optional[Employee], and so on.

This would work for you:

from memory import OwnedPointer

fn main():
    _e = Employee("me", None)

@value
struct Employee:
    var name: String
    var assistant: Optional[OwnedPointer[Employee]]

But right now we’re reworking parts of the standard library so there’s an interface conflict.

Have you tried this code? OwnedPointer doesn’t type check, and ArcPointer seg faults. :upside_down_face:

See my last sentence.

That did not work. Below are the errors that I get:

error: cannot bind type 'OwnedPointer[Employee]' to trait 'Copyable & Movable'
var assistant: Optional[OwnedPointer[Employee]]
                            ~~~~~~~~~~~~^~~~~~~~~~
note: struct 'OwnedPointer[T]' does not implement all requirements for 'Copyable'
note: required function '__copyinit__' is not implemented

But right now we’re reworking parts of the standard library so there’s an interface conflict.

What I was trying to say with this is that there isn’t a good way to do this at the moment in safe Mojo. We’re in the middle of applying some recent advancements to the type system.

It’s not great at the moment. I opted to use a list of arcpointers for my project: prism/src/prism/command.mojo at main · thatstoasty/prism · GitHub

Previously it was an ArcPointer[Optional[Self]] which worked, but Optional[ArcPointer[Self]] did not :slight_smile: