These are chat archives for rust-lang/rust

10th
Feb 2019
Martijn Bakker
@Gladdy
Feb 10 18:55

Could anyone better at rust than me help me work out whether this is the best way of expressing storing a closure in a struct in order to call it later?

struct Sample<'a> {
    b : Box<Fn(u32) -> u32 + 'a>,
}

impl<'a> Sample<'a> {
    fn new<B : 'a + Fn(u32) -> u32>(b : B) -> Self {
        Self {
            b : Box::new(b)
        }
    }
    fn run(&self, i : u32) {
        let x = (self.b)(i);
        println!("{}", x);
    }
}
fn main() {
    let b = Sample::new(|y|{
        y + 1
    });
    b.run(100);
}

It does work, but fn new still looks a bit unclean to me, requiring the generic whereas previously I tried to just use impl Fn(u32)->u32 as the function parameter

Ryan
@rnleach
Feb 10 19:11
@Gladdy , I'm not sure this will work, let me try something.
Ryan
@rnleach
Feb 10 19:16
Ok, it works. I was worried this type might not work in a collection, but I guess that's just for Box<dyn FnOnce()> types. Relevant doc here.
This could get really tough with the borrow checker at times if you try to capture many local variables, using move closures might be helpful there.
Martijn Bakker
@Gladdy
Feb 10 19:18
I try to not capture/use anything, though might be required later
anyway - thanks - I'll keep going along this path trying to work out all of the lifetime issues
Ryan
@rnleach
Feb 10 19:20
Yeah, I understand. Otherwise the code looks good to me. Pretty readable I think. I'm not sure how else to write it.
Martijn Bakker
@Gladdy
Feb 10 19:21
The confusion initially was that Box seems to have an implicit 'static lifetime associated with it
Ryan
@rnleach
Feb 10 19:21
Yes, that's got me before too.
Martijn Bakker
@Gladdy
Feb 10 19:21
not entirely sure why, rather than tying the lifetime to Box itself
Ryan
@rnleach
Feb 10 19:26
I think the why is because you can potentially keep the Box alive for the rest of the program by moving it around, the lifetime defaults to static (which can be pretty restrictive) unless you explicitly give it a different lifetime.
Martijn Bakker
@Gladdy
Feb 10 19:29
That makes sense
Still getting to grips with bits of rust after having done years of C++
so far quite a good experience
SEGFAULT
@IGBC
Feb 10 23:11
is the compiler optimising out the empty while loop?
Denis Lisov
@tanriol
Feb 10 23:14
Do you mean a loop with a finite number of iterations or not?
SEGFAULT
@IGBC
Feb 10 23:17
Sorry I posted this in the wrong chat, due to gitter being unresponsive. I was disussing C, Rust wouldn't do anything so unpredictable :P