[Idiomatic way] Uninitialized resource on struct instance - box vs option

⚓ Rust    📅 2026-02-14    👤 surdeus    👁️ 9      

surdeus

Warning

This post was published 51 days ago. The information described in this article may have changed.

Hello,

I'm trying to find, in rust, in the most idiomatic way, to represent a resource (in a struct) that is to be initialized but in the future. Not in the new function.

Would it be better to use Option or Box ? Or is there a better option ?

In my specific case I have a struct meant to implement the Future trait. The main function of the future that I call (I didn't write the function, the code isn't mine, I use a third C library) has a callback as an argument that is called when the result is ready.

It looks something like this:

struct MyFutureStruct {
     // ...some other ressources....
     result_created: bool,
     waker: Option<Waker> // is this good ? or should I use Box or something else ?
}

impl Future for MyFutureStruct {
   type Output = ...;

    fn poll(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Self::Output> {
       match self.result_created {
           false => {
              // something like this - more like a pseudo code here
              // this callback is called when the result is created and ready to be used 
              self.waker  = Some(ctx.waker().clone());
              let callback = result_created_callback
              // call the main third library function here
              create_result(callback)
           }
           true => {
              // here the callback was called
           }
       }
    }

    fn result_callback_created(user_data) {
       // here user_data is Self
       self.waker.unwrap().wake_by_ref()
       self.result_created = true
    }
}

As you can see, I'm not sure whether Option is the best way to contain the Waker.

Hoping I was clear enough.

Thank you very much in advance for any help.

3 posts - 2 participants

Read full topic

🏷️ Rust_feed