我写了我认为很简单的代码:
#![feature(plugin)]
#![plugin(rocket_codegen)]
extern crate rocket;
extern crate statsd;
use rocket::{Data, Request};
use rocket::fairing::AdHoc;
use statsd::Client;
#[get("/")]
fn index() -> &'static str {
"Hello, World"
}
fn main() {
let mut client = Client::new("127.0.0.1:9125", "miniserver-rs").unwrap();
rocket::ignite()
.attach(AdHoc::on_request(|request, data|{
client.incr("http.requests");
println!("Request URI: {}", request.uri());
}))
.mount("/", routes![index])
.launch();
client.incr("server.bootstrap");
}
我尝试在每个请求上发送一些指标,但我收到以下编译器错误:
Compiling miniserver-rs v0.1.0 (main.rs)
error[E0373]: closure may outlive the current function, but it borrows `client`, which is owned by the current function
--> src\main.rs:19:33
|
19 | .attach(AdHoc::on_request(|request, _data|{
| ^^^^^^^^^^^^^^^^ may outlive borrowed value `client`
20 | client.incr("http.requests");
| ------ `client` is borrowed here help: to force the closure to take ownership of `client` (and any other referenced variables), use the `move` keyword
|
19 | .attach(AdHoc::on_request(move |request, _data|{
| ^^^^^^^^^^^^^^^^^^^^^
error[E0387]: cannot borrow data mutably in a captured outer variable in an `Fn` closure
--> src\main.rs:20:11
|
20 | client.incr("http.requests");
| ^^^^^^
|
help: consider changing this closure to take self by mutable reference
--> src\main.rs:19:33
|
19 | .attach(AdHoc::on_request(|request, _data|{
| _________________________________^
20 | | client.incr("http.requests");
21 | | println!("Request URI: {}", request.uri());
22 | | }))
| |_______^
我知道这client
是在闭包中捕获的,并由另一个函数 ( main
) 拥有,该函数的寿命可能少于闭包。我不能move
这样做,因为Client
没有实现Copy
,所以以后不能使用引用。
我也明白我不能在闭包中借用可变数据(Client
是可变的)。经过大量搜索,我可以得出结论我需要将Arc
/Rc
与Mutex
/ RwLock
/结合使用RefCell
,但在进一步之前,我想确定它是必需的。