I need a trait that allows me to construct a object that borrows an object that borrows something. In the following example that is 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>();
}
I need to create GarbageBins generically determined on a function call, as in the example. This example looks maybe a unnecessary regarding the fixed type Paper in the new() associated function of the Trait. This should become a Trait object in the real code.
How can I realize the creation of garbage_bin the generic type T?
here is the error message that I get, if I un-comment the line:
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,'b, 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,'b, 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>`