我现在正在听取这个问题。我试图将它缩小到一个可重复性最小的例子。
struct Request;
struct ResponseWriter<'a> {
dummy: &'a ()
}
#[deriving(Clone)]
pub struct RouteStore{
pub routes: Vec<Route>,
}
#[deriving(Clone)]
struct Route {
path: String,
handler: fn(request: &Request, response: &mut ResponseWriter)
}
impl RouteStore {
pub fn new () -> RouteStore {
RouteStore {
routes: Vec::new()
}
}
fn add_route (&mut self, path: String, handler: fn(request: &Request, response: &mut ResponseWriter)) -> () {
let route = Route {
path: path,
handler: handler
};
self.routes.push(route);
}
}
fn main () {
}
这让我:
error: mismatched types: expected `fn(&http::server::request::Request, &mut http::server::response::ResponseWriter<>)` but found `fn(&http::server::request::Request, &mut http::server::response::ResponseWriter<>)` (expected concrete lifetime, but found bound lifetime parameter )
src/so.rs:12 handler: fn(request: &Request, response: &mut ResponseWriter)
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
以前我将fn
存储在HashMap
这样HashMap<String, fn(request: &Request, response: &mut ResponseWriter)>
中。这很好。
但是现在我想稍微重构一下并引入一个Route
结构并将内容存储为Vec<Route>
。但是突然地狱破裂了,我不知道如何解决它: - /
对于好奇的人来说,这是我为Rust写一个名为Floor的表达灵感的Web框架的努力的一部分
答案 0 :(得分:4)
让你的例子变得更小(摆脱http
依赖关系),以及IRC上的一些建议(即有人指出如果你从deriving(Clone)
删除问题就会消失Route
),您可以看到下面的固定版本(--cfg v2
)
#[deriving(Clone)]
pub struct RouteStore{
pub routes: Vec<Route>,
}
#[cfg(v1)]
#[deriving(Clone)]
struct Route {
path: String,
handler: fn(response: &mut ())
}
#[cfg(v2)]
struct Route {
path: String,
handler: fn(response: &mut ())
}
#[cfg(v2)]
impl Clone for Route {
fn clone(&self) -> Route {
Route { path: self.path.clone(), handler: self.handler }
}
}
impl RouteStore {
pub fn new () -> RouteStore {
RouteStore {
routes: Vec::new()
}
}
fn add_route (&mut self, path: String, handler: fn(response: &mut ())) -> () {
let route = Route {
path: path,
handler: handler
};
self.routes.push(route);
}
}
fn main () {
}
这里的问题是(编辑:嗯,它 有{{1} }方法,但返回的值似乎与该字段所需的内容不兼容。上面的fn
没有实现Clone
。clone
版本只是对整个问题进行了一步。)
所以我怀疑你看到的错误来自于v2
注入的自动生成的克隆实现。