rest - Cannot borrow captured outer variable in an `Fn` closure as mutable -
this first day rust, i'm trying trivial, , i'm stuck.
what i'm trying add struct vector, , return result. i'm trying create simple rest service store data in memory when posting, , return data in json format when doing get.
this current code:
fn main() { let mut server = nickel::new(); let mut reservations = vec::new(); server.post("/reservations/", middleware! { |request, response| let reservation = request.json_as::<reservation>().unwrap(); reservations.push(reservation); // <-- error occurs here format!("hello {} {}", reservation.name, reservation.email) }); server.listen("127.0.0.1:3000"); }
i tried this solution refcell, error trait sync not implemented vec<reservation::reservation>
this example of how rust protects thread unsafety.
if think it, in current code possible multiple threads try concurrently mutate reservations
without kind of synchronization. data race , rust complain it.
a possible solution wrap reservations
vector mutex
synchronization. need arc
(atomic reference counting), since rust cannot prove reservations
live longer threads.
with these changes, code should following:
use std::sync::{arc, mutex}; fn main() { let mut server = nickel::new(); let reservations = arc::new(mutex::new(vec::new())); server.post("/reservations/", middleware! { |request, response| let reservation = request.json_as::<reservation>().unwrap(); reservations.lock().unwrap().push(reservation); // <-- error occurs here format!("hello {} {}", reservation.name, reservation.email) }); server.listen("127.0.0.1:3000"); }
Comments
Post a Comment