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

2019-09-24 12:22发布

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.

标签: rust lifetime
2条回答
冷血范
2楼-- · 2019-09-24 12:51

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.

查看更多
乱世女痞
3楼-- · 2019-09-24 12:54

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.

查看更多
登录 后发表回答