2

我正在尝试实现一个 Iron 处理程序,其中包含对另一个结构的引用。该结构保存数据并对数据执行所有操作。

[package]
name = "testcrate"
version = "0.1.0"
authors = ["me"]

[dependencies]
iron = "^0.2"

这是代码:

//! Handlers for the server.
extern crate iron;

use iron::{status, middleware};
use iron::IronResult;
use iron::prelude::Set;
use iron::request::Request;
use iron::response::Response;

/// The MyServer struct holds the data and provides methods
/// to manipulate or retrieve that data.
struct MyServer;
impl MyServer {
    pub fn build_response() -> String {
        "response".to_string()
    }   
}

/// The ReadHandler handles the creation of HTTP responses.
pub struct ReadHandler {
    pub server: &MyServer,
}
impl middleware::Handler for ReadHandler {                                                                                         

    /// Return the current status JSON.
    fn handle(&self, req: &mut Request) -> IronResult<Response> {
        let body = self.server.build_response();
        let response = Response::with((status::Ok, body));
        Ok(response)
    }   
}

不幸的是,我收到有关缺少生命周期说明符的错误:

src/lib.rs:22:17: 22:26 error: missing lifetime specifier [E0106]
src/lib.rs:22     pub server: &MyServer,
                              ^~~~~~~~~
src/lib.rs:22:17: 22:26 help: run `rustc --explain E0106` to see a detailed explanation

但是当我添加生命周期说明符时(我还没有完全理解)......

pub struct ReadHandler<'a> {
    pub server: &'a MyServer,
}
impl<'a> middleware::Handler for ReadHandler<'a> {
    // ...
}

...我收到另一条错误消息:

src/lib.rs:24:1: 32:2 error: the type `ReadHandler<'a>` does not fulfill the required lifetime
src/lib.rs:24 impl<'a> middleware::Handler for ReadHandler<'a> {
src/lib.rs:25 
src/lib.rs:26     /// Return the current status JSON.
src/lib.rs:27     fn handle(&self, req: &mut Request) -> IronResult<Response> {
src/lib.rs:28         let body = self.server.build_response();
src/lib.rs:29         let response = Response::with((status::Ok, body));
              ...
note: type must outlive the static lifetime

将有其他处理程序以只读或读写模式访问 MyServer。

添加生命周期说明符的正确方法是什么?还是我可能需要像 Arc 这样的结构?

4

1 回答 1

5

Handler特征是 的子特征Any

pub trait Handler: Send + Sync + Any {
    fn handle(&self, &mut Request) -> IronResult<Response>;
}

并且该Any特征具有'static终生约束:

pub trait Any: Reflect + 'static {
    fn get_type_id(&self) -> TypeId;
}

绑定意味着您的'static结构不能包含引用。您将不得不使用另一种类型的指针。因为Handler也是 and 的一个子特征Send,所以Sync你需要使用Arc, since Rcis not Sendor Sync

于 2015-10-17T17:50:27.970 回答