我想解析 YAML 文件并将服务中的值用于 HTTP 请求。第 35 行是 main 函数的结尾。
extern crate hyper;
extern crate libc;
extern crate yaml_rust;
use hyper::rt::Future;
use hyper::service::service_fn_ok;
use hyper::{Body, Response, Server};
use std::sync::Arc;
use yaml_rust::YamlLoader;
fn main() {
let content: String = String::from("response: Hello world");
let cfg = Arc::new(YamlLoader::load_from_str(content.as_str()).unwrap());
let cfg0 = (&cfg[0]).clone();
let cfg_response = (&cfg0)["response"].as_str().unwrap();
// A `Service` is needed for every connection, so this
// creates on of our `hello_world` function.
let handle = move || {
let cfg_response = cfg_response.clone();
service_fn_ok(move |_| Response::new(Body::from(String::from(cfg_response.clone()))))
};
// Serve HTTP protocol
// This is our socket address...
let addr: std::net::SocketAddr = ([127, 0, 0, 1], 3000).into();
let server = Server::bind(&addr)
.serve(handle)
.map_err(|e| eprintln!("server error: {}", e));
// Run this server for... forever!
hyper::rt::run(server);
}
不幸的是,我遇到了一个导致奇怪借用错误的嵌套闭包:
error[E0597]: `cfg0` does not live long enough
--> src/main.rs:15:26
|
15 | let cfg_response = (&cfg0)["response"].as_str().unwrap();
| ^^^^ borrowed value does not live long enough
...
35 | }
| - borrowed value only lives until here
|
= note: borrowed value must be valid for the static lifetime...
我尝试过了
- 在借用之前克隆它
- 用于
Arc
使其基于计数器, - 修改分配
都无济于事
为什么会这样?我该如何解决这个问题?