我又一次遇到了我似乎无法独自解决的终身问题。
我有这个特点
pub trait MiddlewareHandler: Clone {
fn invoke (&self, req: &Request, res: &mut Response) -> bool {
true
}
// we need this because otherwise clone() would be ambiguous
fn clone_box(&self) -> Box<MiddlewareHandler> {
box self.clone() as Box<MiddlewareHandler>
}
}
impl MiddlewareHandler for fn (req: &Request, res: &mut Response) -> bool {
fn invoke(&self, req: &Request, res: &mut Response) -> bool{
(*self).invoke(req, res)
}
}
impl Clone for Box<MiddlewareHandler> {
fn clone(&self) -> Box<MiddlewareHandler> {
self.clone_box()
}
}
我为 fn (req: &Request, res: &mut Response) -> bool
实现的为了能够接受轻量级的功能和更重的重量MiddlewareHandler
同时实现者。
我将它们存储为 Vec<Box<MiddlewareHandler>>
pub struct Middleware {
handlers: Vec<Box<MiddlewareHandler>>
}
现在,问题是,编译器在这里对我大喊大叫:
pub fn add<T: MiddlewareHandler> (&mut self, handler: T) {
self.handlers.push(box handler);
}
它说:
error: value may contain references; add `'static` bound to `T`
self.handlers.push(box handler);
实现应该与此处使用的非常相似:
https://github.com/iron/iron/blob/master/src/chain/stackchain.rs#L67
但是,我似乎看不出区别:-/
如果有人愿意帮助我,我将代码推送到 github 到 static
分支:
最佳答案
这里的问题是,为了安全地创建一个装箱的特征对象,原始对象不能有任何生命周期参数(除了static
),或者对象本身也需要尊重那个生命周期,这通常是不可能的。要修复它:
pub fn add<T: MiddlewareHandler + 'static> (&mut self, handler: T) {
self.handlers.push(box handler);
}
读起来有点奇怪,但它说“T
需要实现 MiddlewareHandler
并且它不能包含任何没有 static
的引用生命周期”。这仅适用于 static
。
关于rust - 如何修复 : value may contain references; add `' static` bound to `T` ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24375771/