How to share vector ownership

Hi, I'm really new at Rust's world and I was wondering how push a vector without taking the ownership of the vector inside a callback

let mut users: Vec<User> = vec![];
submit.set_callback(move |_| {
    if name_input.value().len() > 0 || age_input.value().len() > 0 {
        println!("{}, {}", name_input.value(), age_input.value());
        let user = User {name: name_input.value().to_string(), age: to_u8(age_input.value())};
        name_input.set_value("");
        age_input.set_value("");
        //i wanna do this but not taking the ownership here
        users.push(user)
    }
})

Sorry about my bad english :grimacing:

If you need to move name_input and age_input, but not users, you can try

let mut users: Vec<User> = vec![];
let mut_users = &mut users;
submit.set_callback(move |_| {
    // ...
    mut_users.push(user);
});

To move the borrow (mut_users) instead. This may or may not work with set_callback, depending on what bounds it sets.

If you don't need to move anything, try just removing the move keyword.

If it doesn't work, let us know the error from cargo check and the signature of set_callback, and perhaps the value related methods as well.

1 Like

Here is the signature of set_callback

fltk::button::Button
fn set_callback<F>(&mut self, cb: F)
where
    F: FnMut(&mut Self) + 'static,

and here's the output of cargo check

error[E0597]: `users` does not live long enough
  --> src/main.rs:30:21
   |
30 |       let mut_users = &mut users;
   |                       ^^^^^^^^^^ borrowed value does not live long enough
31 | /     submit.set_callback(move |_| {
32 | |         if name_input.value().len() > 0 || age_input.value().len() > 0 {
33 | |             println!("{}, {}", name_input.value(), age_input.value());
34 | |             let user = User {name: name_input.value().to_string(), age: to_int_u(age_input.value())};
...  |
42 | |         }
43 | |     });
   | |______- argument requires that `users` is borrowed for `'static`
...
51 |   }
   |   - `users` dropped here while still borrowed

You need to change Vec<User> to Arc<Mutex<Vec<User>>> and let the closure take ownership of a clone of the Arc-wrapped vector.

Arc enables multiple owners. Mutex enables mutating from multiple places.

3 Likes

Yeah, I wondered if there might be a 'static involved with the callback. That basically means "the type (the closure in this case) cannot contain any borrows (non-'static lifetimes)".

It sounds like you may need shared ownership -- like an Arc<Mutex<Vec<User>>>. See this chapter of the book.

3 Likes

@kornel @quinedot thanks for the help :grinning:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.