Cannot borrow captured outer variable in an `Fn` closure as mutable

╄→尐↘猪︶ㄣ 提交于 2019-12-03 23:37:33
aochagavia

This is a very good example of how Rust protects you from thread unsafety.

If you think about it, in your current code it would be possible that multiple threads try to concurrently mutate reservations without any kind of synchronization. This is a data race and Rust will complain about it.

A possible solution would be to wrap the reservations vector into a Mutex to get synchronization. You will also need an Arc (atomic reference counting), since Rust cannot prove that reservations will live longer than the threads.

With these changes, your code should be like the 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");
}

You can check the documentation for additional info about Mutex and Arc.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!