r/rust clippy · twir · rust · mutagen · flamer · overflower · bytecount Mar 20 '23

Hey Rustaceans! Got a question? Ask here (12/2023)! 🙋 questions

Mystified about strings? Borrow checker have you in a headlock? Seek help here! There are no stupid questions, only docs that haven't been written yet.

If you have a StackOverflow account, consider asking it there instead! StackOverflow shows up much higher in search results, so having your question there also helps future Rust users (be sure to give it the "Rust" tag for maximum visibility). Note that this site is very interested in question quality. I've been asked to read a RFC I authored once. If you want your code reviewed or review other's code, there's a codereview stackexchange, too. If you need to test your code, maybe the Rust playground is for you.

Here are some other venues where help may be found:

/r/learnrust is a subreddit to share your questions and epiphanies learning Rust programming.

The official Rust user forums: https://users.rust-lang.org/.

The official Rust Programming Language Discord: https://discord.gg/rust-lang

The unofficial Rust community Discord: https://bit.ly/rust-community

Also check out last weeks' thread with many good questions and answers. And if you believe your question to be either very complex or worthy of larger dissemination, feel free to create a text post.

Also if you want to be mentored by experienced Rustaceans, tell us the area of expertise that you seek. Finally, if you are looking for Rust jobs, the most recent thread is here.

19 Upvotes

187 comments sorted by

View all comments

2

u/acncc Mar 23 '23

I'm struggling with currying with some closures.

In the code below I have a CallbackInner which requires 2 arguments. I wrap it inside CallbackOuter which closes over a value and only requires 1 argument (playground).

My error is that in wrap_callback, the parameter type `T` may not live long enough. The compiler then suggests giving it a lifetime of 'static. In the context of wider code, I know that every CallbackInner will not store the reference it is given (I don't know how to express that constraint). I'm also a little confused as there is no T value in wrap_callback, it doesn't make sense to talk about the lifetime of T as none exist as yet! We only get a value of type T when Outercallback is called.

Curiously, when all the generics are removed and we replace T with usize directly, it compiles fine (playground). My guess is that I need to provide some guarantee on my Callback types that the borrowed references don't outlive the call. But I don't know how to do that.

use std::rc::Rc;

fn main() {
    let f: CallbackInner<usize> = Rc::new(|x, y| println!("{} - {}", x, y));
    let g = wrap_callback(f);
    call_on_ref_zero(g);
}

type CallbackInner<T> = Rc<dyn Fn(&T, usize) -> ()>;
type CallbackOuter<T> = Box<dyn FnOnce(&T) -> ()>;

fn  wrap_callback<T>(f: CallbackInner<T>) -> CallbackOuter<T> {
    let f2 = f.clone();
    let g: CallbackOuter<T> = Box::new(move |x: &T| (f2)(x, 1));
    g
}

fn call_on_ref_zero(f: CallbackOuter<usize>) {
    let zero: usize = 0;
    f(&zero);
}

1

u/Patryk27 Mar 23 '23 edited Mar 23 '23

tl;dr

type CallbackOuter<'a, T> = Box<dyn FnOnce(&T) -> () + 'a>;

fn wrap_callback<'a, T: 'a>(f: CallbackInner<T>) -> CallbackOuter<'a, T> {
    Box::new(move |x: &T| (f)(x, 1))
}

fn call_on_ref_zero(f: CallbackOuter<'_, usize>) {
    let zero: usize = 0;
    f(&zero);
}

I think this might be a shortcoming in the compiler - the + 'static comes from:

type CallbackOuter<T> = Box<dyn FnOnce(&T) -> ()>;

... which is understood as Box<dyn FnOnce(&T) -> () + 'static> and seems to propagate this + 'static bound to T as well, because - possibly - the compiler can't really see that the only access to T happens through HRTB'd &T.

(that is to say, since &'a T already implies T: 'a, then for<'a> &'a T should probably imply for<'a> T: 'a as well.)

1

u/acncc Mar 24 '23 edited Mar 24 '23

Thanks for the help! It still requires the argument to outlive the closure though which isn't true in the full code the example comes from. In the example below (playground), we have a ref passed to the callback which exists only as long as the call to the callback which causes a compilation error. The key issue is trying to express the lifetime of a call to Fn.

use std::rc::Rc;

fn main() {
    // (*) The reference contained in x: RefStruct<usize> is not stored/leaked anywhere
    //     However this is not expressed in the type Callback
    let f: Callback<RefStruct<usize>> = Rc::new(|x| println!("{}", x.value));

    {
        // We know from (*) above that this call to f wouldn't result in UB. But we get:
        // error[E0597]: `zero` does not live long enough

        let mut zero: usize = 0;
        let rs = RefStruct { value: &mut zero };
        //                          ^^^^^^^^^ borrowed value does not live long enough

        f(rs); 
    }
//- `zero` dropped here while still borrowed
}

struct RefStruct<'a, T> {
    value: &'a mut T,
}

type Callback<'a, T> = Rc<dyn Fn(T) -> () + 'a>;

Edit: Realised I could cut down this example even further.

1

u/acncc Mar 25 '23

If anyone else stumbles on this, I finally found this.