How do I set the return value's lifetime? [clo

2019-09-24 12:29发布

问题:

I have the following method to check if an String ID exists. If it doesn't, generate and then return it:

fn generate_id(&self) -> ID<'m> {
    let id = nanoid::generate(15);
    while self[&id].is_some() {
        id = nanoid::generate(15);
    };
    id
}

ID is a type alias: type ID<'id> = &'id String;

The return value needs to be &'m std::string::String but id is std::string::String.

I have tried doing:

let id: ID<'m> = nanoid::generate(15);

but then it gives the same error that the method is giving only for id.

回答1:

Lifetimes are descriptive, not prescriptive. You don't set lifetimes; they are a consequence of the program you write.

You are trying to return a reference to a local variable. That is not valid, and there is no lifetime you can write to make it valid.

You have an X/Y problem. The real question is why you feel the need to return a reference.



回答2:

You need to focus on where the variable is set, not where you actually return the variable.

In this case, change nanoid::generate(15); to &nanoid::generate(15);:

fn generate_id(&self) -> ID<'m> {
    let id: ID<'m> = &nanoid::generate(15);
    while self[&id].is_some() {
        id = &nanoid::generate(15);
    };
    id
}

This ensures that the initial type of the variable has the lifetime and supplying the value as a reference ensures that the variable has the correct lifetime.



标签: rust lifetime