How to have a higher-ranked lifetime that is outlived by another

Here I'm trying to have StructValue have StructOfValues as a supertrait, unfortunately I'd need something like StructValue<'ctx>: for<'scope where 'ctx: 'scope> StructOfValues<'ctx, 'scope> which I don't know how to write in Rust.

use core::cell::Cell;
use core::marker::PhantomData;

struct Ctx<'ctx>(PhantomData<Cell<&'ctx ()>>);

trait Value<'ctx> {}

struct Val<'ctx, 'scope, T: Value<'ctx>>(PhantomData<(&'scope Cell<&'ctx ()>, T)>);

trait StructOfValues<'ctx: 'scope, 'scope> {
    type Type: 'scope;
}

struct S {
    a: u8,
}

impl<'ctx> Value<'ctx> for S {}
impl<'ctx> Value<'ctx> for u8 {}

struct StructOfValuesForS<'ctx, 'scope> {
    a: Val<'ctx, 'scope, u8>,
}

impl<'ctx: 'scope, 'scope> StructOfValues<'ctx, 'scope> for S {
    type Type = StructOfValuesForS<'ctx, 'scope>;
}

trait StructValue<'ctx>: Value<'ctx> + for<'scope> StructOfValues<'ctx, 'scope> {}

impl<'ctx> StructValue<'ctx> for S {}

(Playground)

Errors:

   Compiling playground v0.0.1 (/playground)
error: implementation of `StructOfValues` is not general enough
  --> src/lib.rs:31:12
   |
31 | impl<'ctx> StructValue<'ctx> for S {}
   |            ^^^^^^^^^^^^^^^^^ implementation of `StructOfValues` is not general enough
   |
   = note: `S` must implement `StructOfValues<'ctx, '0>`, for any lifetime `'0`...
   = note: ...but it actually implements `StructOfValues<'1, '_>`, for some specific lifetime `'1`

error: aborting due to previous error

error: could not compile `playground`

To learn more, run the command again with --verbose.

You could make the lifetime relationship part of StructValue's signature as well.

1 Like

Yeah, that works, but I was hoping to avoid that since it means I'd have to add 'scope to a whole bunch of code that depends on StructValue

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.