Full code:
enum NativeInstance<'a> {
A(&'a AInstance)
}
trait Instance {
fn native(&self) -> NativeInstance;
}
pub struct AInstance;
impl Instance for AInstance {
fn native(&self) -> NativeInstance {
NativeInstance::A(self)
}
}
fn a_instance(instance: &impl Instance) -> &AInstance {
match instance.native() {
NativeInstance::A(A) => A,
}
}
///adapter
enum NativeAdapter<'a> {
A(&'a AAdapter<'a>),
}
trait Adapter<'a> {
fn enumerate(instance: &'a impl Instance) -> Vec<Self> where Self: Sized;
fn native(&self) -> NativeAdapter;
}
pub struct AAdapter<'a> {
instance: &'a AInstance,
}
impl<'a> Adapter<'a> for AAdapter<'a> {
fn enumerate(instance: &'a impl Instance) -> Vec<Self> where Self: Sized {
let instance = match instance.native() {
NativeInstance::A(instance) => instance,
};
///enumerate...
let mut e = Vec::new();
e.push(Self {
instance
});
e
}
fn native(&self) -> NativeAdapter {
NativeAdapter::A(self)
}
}
trait Device<'a> {
fn new(adapter: &'a impl Adapter<'a>) -> Self where Self: Sized;
}
struct ADevice<'a> {
adapter: &'a AAdapter<'a>,
}
impl<'a> Device<'a> for ADevice<'a> {
fn new(adapter: &'a impl Adapter<'a>) -> Self where Self: Sized {
let adapter = match adapter.native() {
NativeAdapter::A(a) => a,
};
Self {
adapter
}
}
}
fn adapter_new(instance: & impl Instance) -> impl Adapter {
AAdapter::enumerate(instance).pop().unwrap()
}
fn device_new<'a>(adapter: &'a impl Adapter<'a>) -> impl Device<'a> {
ADevice::new(adapter)
}
#[test]
fn main() {
let a = AInstance;
let aref = a_instance(&a);
//let adapter = AAdapter::enumerate(&a).pop().unwrap();
//let device = ADevice::new(&adapter);
let adapter = adapter_new(&a);
let device = device_new(&adapter);
}
Error:
error[E0597]: `adapter` does not live long enough
--> tests/impl_trait.rs:95:29
|
95 | let device = device_new(&adapter);
| ^^^^^^^^ borrowed value does not live long enough
96 | }
| -
| |
| `adapter` dropped here while still borrowed
| borrow might be used here, when `adapter` is dropped and runs the destructor for type `impl Adapter<'_>`
It's been a long time since I have problems with lifetimes but this one I can't solve for days and I have no idea where the error is, the message is absurdly vague.
Edit:
This snippet compiles:
let adapter = AAdapter::enumerate(&a).pop().unwrap();
let device = ADevice::new(&adapter);
Does not compile
let adapter = adapter_new(&a);
let device = ADevice::new(&adapter);