问题描述
我需要一个特性,它允许我构造一个借用对象的对象。在下面的例子中就是 PaperBin。 https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=78fb3f88b71bc226614912001ceca65b
trait GarbageBin<'a,'b>{
fn new(rubbish: &'b Paper<'a>) -> Self;
}
struct PaperBin<'a,'b> {
rubbish: &'b Paper<'a>
}
struct Paper<'a> {
matter: &'a [u8]
}
impl<'a,'b> GarbageBin<'a,'b> for PaperBin<'a,'b> {
fn new(rubbish: &'b Paper<'a>) -> Self{
Self {
rubbish: rubbish
}
}
}
fn create_bin_with_rubbish<'a,'b,T>()
where T: GarbageBin<'a,'b>
{
let matter = &[1][..];
let rubbish = Paper{matter};
This gives an error:
//let garbage_bin = T::new(&rubbish);
}
#[test]
fn run() {
create_bin_with_rubbish::<PaperBin>();
}
我需要创建一般根据函数调用确定的 GarbageBins,如示例中所示。对于 Trait 的 new() 关联函数中的固定类型 Paper,此示例看起来可能是不必要的。这应该成为实际代码中的 Trait 对象。
如何实现泛型类型T的garbage_bin的创建?
这是我收到的错误消息,如果我取消注释该行:
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'a` due to conflicting requirements
--> src\reference_to_reference\mod.rs:23:23
|
23 | let garbage_bin = T::new(&rubbish);
| ^^^^^^
|
note: first,the lifetime cannot outlive the lifetime `'a` as defined on the function body at 18:28...
--> src\reference_to_reference\mod.rs:18:28
|
18 | fn create_bin_with_rubbish<'a,T>()
| ^^
note: ...but the lifetime must also be valid for the lifetime `'b` as defined on the function body at 18:31...
--> src\reference_to_reference\mod.rs:18:31
|
18 | fn create_bin_with_rubbish<'a,T>()
| ^^
note: ...so that the types are compatible
--> src\reference_to_reference\mod.rs:23:23
|
23 | let garbage_bin = T::new(&rubbish);
| ^^^^^^
= note: expected `GarbageBin<'_,'_>`
found `GarbageBin<'a,'b>`
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)