9 ms·
Thanks for your reply. I'm still trying to understand what the restrictions look like. Say I sometimes have an outstanding asynchronous operation, i.e. validat
by ridiculous_fish 10y ago
Thanks for your reply. I'm still trying to understand what the restrictions look like.
Say I sometimes have an outstanding asynchronous operation, i.e. validating some text in a document. I want to represent this by storing a Future representing this operation:
struct Document {
text:String,
validating: Option<Future<Bool>>
};
It seems like there's a problem: in order to have a struct of this type, we need to have the type of the Future, but the only way to have the type of the Future is to create the Future (and here we have None).
It this struct possible? How would I initialize it with {"foo", None}?
- grayrest 10y agoThe construct wouldn't be valid as written for the reasons you mention. The blog post for this discussion glosses over the details by writing `impl Future<Item = Bool>` instead of the concrete type a future would have to have in Rust today. I'm not an expert but one of the ongoing dicussions in the impl Trait RFC is where the construct can show up. The preliminary version can only appear as a return type from a function where the compiler can always determine the exact details at compile time depending on the chain of calls. I believe typing out the entire type of the future in the struct would work but, again, I only somewhat know my way around the language.
- steveklabnik 10y agoOne solution is to put the Future into a Box.
- steveklabnik 10y agoAnd I can't believe I missed this, but the other way is to make the struct generic over a type implementing Future.
- ridiculous_fish 10y agoDoes this work though? How do you create an instance of the struct without an instance of the Future?
- steveklabnik 10y agotrait Future {} struct DynamicFoo { text:String, validating: Option<Box<Future>> } struct StaticFoo<T: Future> { text:String, validating: Option<T> } These are the two options. In the first, Box<Future> stores a "trait object", that is, a tuple of (data ptr, vtable ptr). In the second, there will be a struct for each type used to generate a StaticFoo. impl Future for i32 {} impl Future for f64 {} fn main() { let d = DynamicFoo { text: String::from("foo"), validating: Some(Box::new(5) as Box<Future>), }; let s1 = StaticFoo { text: String::from("foo"), validating: Some(5), }; let s2 = StaticFoo { text: String::from("foo"), validating: Some(5.0), }; } Works just fine.