如何设置返回值的生命周期? [英] How do I set the return value's lifetime?
问题描述
我有以下方法检查String
ID是否存在.如果没有,请生成然后返回:
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
是类型别名:type ID<'id> = &'id String;
返回值必须为&'m std::string::String
,但id
为std::string::String
.
我尝试做:
let id: ID<'m> = nanoid::generate(15);
,但是它给出的错误与方法仅针对id
的错误相同.
but then it gives the same error that the method is giving only for id
.
推荐答案
生命周期是描述性的,而不是描述性的.您没有设置生命周期;它们是您编写的程序的结果.
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.
您遇到X/Y问题.真正的问题是为什么您感到需要返回引用.
You have an X/Y problem. The real question is why you feel the need to return a reference.
这篇关于如何设置返回值的生命周期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!