【发布时间】:2021-06-06 14:49:46
【问题描述】:
我正在尝试在一个小型 Rust 程序中添加一个网络服务器 (hyper),但遇到了移动问题。
//main.rs
// Suppose this is something meaningful and used in multiple places inside `main`
let test: String = "Foo".to_string();
// ...
// This comes from here: https://docs.rs/hyper/0.14.8/hyper/service/fn.service_fn.html
// Determines what the web server sends back
let make_svc = make_service_fn(|_conn| async {
Ok::<_, Infallible>(service_fn(|req: Request<Body>| async move {
// I need to somehow read the value of `test` here as well
if req.version() == Version::HTTP_11 {
Ok(Response::new(Body::from(test)))
} else {
Err("not HTTP/1.1, abort connection")
}
}))
});
这会产生以下问题:
我知道 String 不能具有 Copy 特征(最终我将需要使用其他更复杂的类型)。本质上,我想借用或使用变量的克隆,因为变量也将在 hyper 的处理程序之外使用(例如,它可以记录到文件或用于随着时间的推移汇总统计信息)。
所以我的问题是,它是如何工作的?我如何需要重构闭包,以便我可以以某种方式访问在 main 中定义(以及以其他方式使用)的变量的值?
【问题讨论】:
-
你可以克隆它,或者例如创建一个
Arc。 -
@Netwave 我尝试在内部和外部克隆它,但仍然是同样的问题。我会研究 Arc,谢谢!