The proper way to use lifetime for a structure with a reference on an element of an owned list?

What is a proper way of doing this in Rust?

use std::collections::LinkedList;
type Cell = [ i32; 2 ];


fn main()
  let object = Object::new();

pub struct Object< 'a >
  pub body : LinkedList< Cell >,
  pub head : &'a Cell,
  pub tail : &'a Cell,

impl< 'a > Object< 'a >
  pub fn new() -> Self
    let mut body : LinkedList<Cell> = LinkedList::new();
    body.push_back([ 2, 3 ]);
    body.push_back([ 1, 3 ]);
    body.push_back([ 0, 3 ]);
    let head = body.iter().nth( 0 ).unwrap();
    let tail = body.iter().nth( body.len()-1 ).unwrap();
    Self { body, head : &head, tail : &tail }

Playground with the code.
Tail and head live as long as list live, but how to communicate that compiler?
Is it possible to eliminate < 'a > from pub struct Object< 'a >?

You look to be trying to make a self-referential structure, this is not possible with standard Rust references, and not recommended in general.

Since LinkedList has the methods front() and back() why not just use those instead of keeping references around yourself?


It's not possible for an object to contain a temporary borrow anything from itself.

You can wrap elements in Arc and have a shared reference this way.

In some cases you could try using Vec or VecDeque and refer to elements by their index.

1 Like

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.