Understanding (Static) Lifetimes

The most important thing here is that you don't want impl EntityImporter { here. It's unfortunate that the error message suggests "indicate the anonymous lifetimes: <'_, '_>" -- that's a good suggestion for function parameter types, but questionable for an inherent impl block.

The thing you're looking for to get past all these errors is this:

impl<'a, 'b> EntityImporter<'a, 'b> {
    pub fn new(repos: &'a Vec<Repository>, pool: &'b EntityPool) -> EntityImporter<'a, 'b> {
        EntityImporter {
            repositories: repos,
            entity_pool: pool,
        }
    }
}

Because this is basically a -> Self method, and you need to tie the lifetimes of the parameters to the lifetimes that are put on the struct, since you're putting those parameters into the struct.


Now, that said, you almost certainly don't want references inside your struct here. References in structs are not "I am trying to do something seemingly simple here" -- they're "the evil-hardmode of Rust".

Just keep owned values in your struct, like

pub struct EntityImporter {
    repositories: Vec<Repository>,
    entity_pool: EntityPool,
}

impl EntityImporter {
    pub fn new(repos: Vec<Repository>, pool: EntityPool) -> EntityImporter {
        EntityImporter {
            repositories: repos,
            entity_pool: pool,
        }
    }
}

(And if you do want references, you still don't want &Vec<T>, because &[T] lets you do all the same things but is more general.)

5 Likes