jpernst / rental

Rust macro to generate self-referential structs
Apache License 2.0
211 stars 11 forks source link

ref_rent() returning Option<&'suffix value> #15

Closed MarkSwanson closed 7 years ago

MarkSwanson commented 7 years ago

So it turns out that it's common for me to have to return an Option that contains the reference instead of the reference directly.

It's like I need a ref_rent_option() :-)

Otherwise I need to return references that would never be used in real life, and match on that. Example: I'd like to just return get_key_value() -> which returns Option<&str>. But I can't because ref_rent() can't return an Option :-)

So... silly hackery is required like this?

Some(rent_context) => {
                let value = rent_context.ref_rent(|new_request_v3| {
                    match new_request_v3.get_things() {
                        Ok(things) => {
                            SomeHelper::get_key_value(&things, &k).unwrap_or("match_this_fail_string_to_detect_not_found")
                        },
                        Err(e) => "match_this_fail_string_to_detect_not_found"
                    }
                });
                Some(value)
            },
            None => None

:-D

MarkSwanson commented 7 years ago

Maybe this would work?

    pub fn ref_rent_option<__F, __R>(&self, f: __F) -> Option<&__R> where
           __F: for<#(#suffix_rlt_args,)*> FnOnce(#borrow_suffix_ty) -> Option<&#last_rlt_arg __R>,
           __R: 'static + ?Sized //#(#struct_lt_args +)*,
       {
           f(#borrow_suffix_expr)
        }
jpernst commented 7 years ago

Until we get ATCs, this is probably a reasonable thing to add, since it can't be done more generally. I've just published version 0.4.10 with the new methods maybe_ref_rent for Options, and try_ref_rent for Results, with corresponding mut and all versions. Hopefully that covers all bases.

MarkSwanson commented 7 years ago

Great! Thanks for addressing this so quickly!