Hi!
I want to create a data structure that looks kind of like this:
pub struct NestedRef<'a>(Option<&'a mut NestedRef<'a>>);
#[test]
fn test_scoped_ref() {
let mut a = NestedRef(None);
{
NestedRef(Some(&mut a));
}
NestedRef(Some(&mut a));
}
Unfortunately, that doesn't compile because of a borrow conflict. I think the issue is that I'm using the same lifetime for everything, but I actually want the inner-nested lifetimes to be shorter.
Okay, can I just give it two lifetimes? Well technically that does solve the case above but it only allows for a single level of nesting. I'd like to have limitless nesting, but the code below doesn't compile:
pub struct NestedRef2<'a, 'b>(Option<&'a mut NestedRef2<'b, 'b>>);
#[test]
fn test_nested_ref_2() {
let mut a = NestedRef2(None);
{
let mut b = NestedRef2(Some(&mut a));
{
NestedRef2(Some(&mut b));
}
NestedRef2(Some(&mut b));
}
NestedRef2(Some(&mut a));
}
My intuition is that the approach above would be a dead end because I think a new lifetime parameter is needed for every additional level of nesting. Is there a way around this?
I think using a trait accomplishes what I want. Is there a simpler way, though?
pub trait Nesty {}
// Kind of crazy base case
impl Nesty for () {}
pub struct NestedRef3<'a, N: Nesty>(Option<&'a mut N>);
impl<'a, N: Nesty> Nesty for NestedRef3<'a, N> {}
#[test]
fn test_nested_ref_3() {
let mut a = NestedRef3::<'_, ()>(None);
{
let mut b = NestedRef3(Some(&mut a));
{
NestedRef3(Some(&mut b));
}
NestedRef3(Some(&mut b));
}
NestedRef3(Some(&mut a));
}
Thanks for your help!