我试图实现一个包含对另一个结构的引用的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这样的结构?
答案 0 :(得分:5)