Cannot infer an appropriate lifetim

Hello!

I have such a thing:

type G2d<'a> = GfxGraphics<'a, Resources, CommandBuffer>;

How to include it as a field into a structure? I tried:

pub struct Dc
{
  g : G2d,
  c : Context,
}

It gives:

expected named lifetime parameter

I tried:


pub struct Dc
{
  g : &'a mut G2d<'a>,
  c : Context,
}

window.draw_2d( &event, | c, g, device |
{
  let mut dc = Dc { c, g };
});

But it gives:

I would appreciate any help.

lifetime annotations on &mut are intentionally completely inflexible (AKA "invariant"). They have to always exactly mean the whole lifetime of the thing that has been borrowed.

But it's logically impossible that the outer &mut borrow has been created exactly at the same moment as a reference inside G2d<'a> was.G2d had to be created first, and only then could have been borrowed. So in the expression &'a mut G2d<'a> these both 'a lifetimes can't possibly mean they borrow the same thing.

Use two different lifetimes, because borrow of G2d itself as a whole is borrowing a different thing than the 'a that refers to some other data borrowed inside of G2d.

With shared references when you write &'a Something<'a>, the compiler can ignore the paradox, because it's safe to pretend lifetimes of immutable are shorter than they are, so the compiler quietly makes it work. With mutable references it has to be strict to avoid creating loopholes.

2 Likes

Thank you for the response. It make sense.
I changed code to:

pub struct Dc<'a>
{
  g : G2d<'a>,
  c : Context,
}

But now I have this:


Any idea how to fix that problem?

Proper solution is

pub struct Dc<'a, 'b>
{
  g : &'a mut G2d<'b>,
  c : Context,
}

@kornel thank you for your hint, it helped me to find the solution.

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.