gpt4 book ai didi

rust - 如何修复 : expected concrete lifetime, 但找到绑定(bind)的生命周期参数

转载 作者:行者123 更新时间:2023-11-29 08:24:09 25 4
gpt4 key购买 nike

我目前正在全力以赴。我试图将其缩小为最小的可重现示例。

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)
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

enter image description here

之前我存储了我的 fnHashMap像这样HashMap<String, fn(request: &Request, response: &mut ResponseWriter)> .这很好用。

但现在我想重构一下并引入一个 Route将事物构造并存储为 Vec<Route> .但是突然间 hell 破灭了,我不知道如何解决它:-/

对于好奇的人,这是我为 Rust 编写一个受 expressjs 启发的 Web 框架的一部分,名为 Floor

最佳答案

在使您的示例更小一些(摆脱 http 依赖项)之后,以及 IRC 上的一些建议(即有人指出,如果您删除 deriving,问题就会消失(Clone) from the 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 () {

}

这里的问题是 fn 没有实现 Clone(编辑:好吧,它确实有一个 clone 方法,但返回的值似乎与该字段的需要不兼容。上面的 v2 版本只是回避了整个问题。)

所以我怀疑您看到的错误来自 deriving(Clone) 注入(inject)的自动生成的克隆实现。

关于rust - 如何修复 : expected concrete lifetime, 但找到绑定(bind)的生命周期参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24162518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com