These are chat archives for rust-lang/rust

28th
Feb 2016
dafixa
@dafixa
Feb 28 2016 14:44
is this the official Rust chat, or is there an IRC channel?
not much going on here
Peter Atashian
@retep998
Feb 28 2016 14:50
@dafixa irc.mozilla.org #rust
Jarred Nicholls
@jnicholls
Feb 28 2016 14:51
^^
Dmitry Golubets
@DGolubets
Feb 28 2016 18:53
hi, I'm finally learning Rust.. ) I don't fully grasp rust memory model, so I would appreciate if someone can help me with my simple toy-app:
// doesn't work, need a lifetime..
// thread_local!(static HOOKS: Vec<Hook> = vec![]);

struct Hook<'a> {
    handler: Box<Fn(u64) -> bool + 'a>
}

impl<'a> Hook<'a> {
    fn new<H>(handler: H) -> Hook<'a> where H: Fn(u64) -> bool + 'a  {
        let hook = Hook {
            handler: Box::new(handler)
        };

        // HOOKS.with(|hooks| {
        //     hooks.push(hook);
        // });

        hook
    }
}

impl<'a> Drop for Hook<'a> {
    fn drop(&mut self) {
        // remove it from HOOKS
    }
}
I'm trying to create a "wrapper" for Windows hook
I want a Hook::new to create a Hook, that automatically drops when out o scope
The problem is I also need to store it in global (or at least thread local) list
but I can't do it, cos there is no way I specfy lifetime for it..
How do you approach such problem in Rust?
Erik Hedvall
@Ogeon
Feb 28 2016 19:38

You simply can't have a variable lifetime (i.e. non-static references) if you want to keep you hook in a static container. Have you tried with this?

struct Hook {
    handler: Box<Fn(u64) -> bool + 'static>
}

You won't be able to use references in your handler, unless they are static, as well.

Dmitry Golubets
@DGolubets
Feb 28 2016 19:54
Yeah, static works, but as you've said, it allows no references in handler..
Jarred Nicholls
@jnicholls
Feb 28 2016 20:39
@DGolubets Probably need an Rc instead of Box, and you can have multiple references to it. http://is.gd/9yiiCP
Erik Hedvall
@Ogeon
Feb 28 2016 21:58
Static means basically available forever and non-static references cannot be available forever, since their original values will eventually drop out of their scopes. What you can have, on the other hand, is reference counted (Rc or Arc). Their data will live on the heap, so they can easily be stored in a 'static closure.