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

爷,独闯天下 提交于 2019-12-13 22:48:45

问题


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.



来源:https://stackoverflow.com/questions/49581900/how-do-i-set-the-return-values-lifetime

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!