0

我想解析 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...

我尝试过了

  1. 在借用之前克隆它
  2. 用于Arc使其基于计数器,
  3. 修改分配

都无济于事

为什么会这样?我该如何解决这个问题?

4

1 回答 1

0

您将闭包传递给的函数 -hyper::server::Builder::serve并且hyper::rt::run()- 要求它们的参数是'static,而不是受任何函数的限制。 main在这方面不被认为是特殊的。

限制它的值cfg_response, 被外部闭包捕获,因此嵌套闭包不是获取错误所必需的。这是一个具有相同问题的非常小的程序:

fn main() {
    let cfg0 = String::from("hello world");
    let cfg_response: &str = &cfg0;

    let handle = move || {
        // this closure takes ownership of cfg_response, a reference to cfg0.  Since cfg0 will not
        // outlive the function, neither can handle.  If it instead took ownership of cfg0 or a
        // clone of it, it would have no outside references and could live forever.
        return cfg_response.to_owned();
    };

    serve(handle);
}

fn serve<F: Fn() -> String + 'static>(handle: F) {
    loop {
        println!("{}", handle());
    }
}

正如@Stargateur 指出的那样,这可以通过cfg_response拥有来解决。

或者,您可以cfg0像这样在lazy_static 中初始化:

#[macro_use]
extern crate lazy_static;

lazy_static! {
    static ref cfg0: String = String::from("hello world");
}

这样,您仍然可以使用借来的值,因为它符合生命周期要求。

于 2018-09-20T19:13:03.327 回答