1

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 body, but how to communicate that to the compiler? Is it possible to eliminate <'a> from pub struct Object<'a>?

user2722968
  • 13,636
  • 2
  • 46
  • 67
Kos
  • 1,547
  • 14
  • 23
  • Is keeping `head` and `tail` necessary here? `LinkedList` has [`front()`](https://doc.rust-lang.org/std/collections/struct.LinkedList.html#method.front) and [`back()`](https://doc.rust-lang.org/std/collections/struct.LinkedList.html#method.back) methods for this purpose. – kmdreko Jul 25 '21 at 16:49

0 Answers0