延长锈蚀寿命 [英] Expanding Rust Lifetime
问题描述
我有一些需要解决的代码.这是一个小辅助函数,应将Vec<&str>
返回给调用函数.不过,我似乎无法正确地选择一生.
I have a bit of code that I'm fighting with. It's a little helper function that should return a Vec<&str>
to the calling function. I can't seem to get the lifetime right, though.
这是代码段:
fn take_symbol<'a>(ch: &'a str, current: &'a mut String) -> &'a mut TokenList<'a> {
let out = TokenList::<'a>::new();
out.push(current.as_str());
out.push(ch);
*current = String::new();
&mut out
}
编译器告诉我:error: 'out' does not live long enough
并且该引用在'a
的生存期内必须是有效的,但是在我看来,它就像为'a
定义的一样.
The compiler is telling me: error: 'out' does not live long enough
and that the reference must be valid for the lifetime of 'a
, but it looks to me like it is defined for 'a
.
我也尝试将其更改为:
let out = &mut TokenList::<'a>::new();
,它不会更改任何错误消息.或者:
which doesn't change any of the error messages. Or:
let out = &'a mut TokenList::<'a>::new();
编译器根本不喜欢的.
如何定义out
的生存期为'a
?
有关更多详细信息,这是我对TokenList的定义:
For further details, here is my definition of TokenList:
pub type Token<'a> = &'a str;
pub type TokenList<'a> = Vec<Token<'a>>;
推荐答案
out
的生存期不是'a
,因为out
在函数末尾被破坏了. Rust不允许您返回对其的引用(它将允许访问释放的内存!).
The lifetime of out
is not 'a
, since out
is destroyed at the end of the function. Rust will not allow you to return a reference to it (it would allow accessing freed memory!).
尝试将功能更改为以下内容:
Try changing your function to the following:
fn take_symbol<'a>(ch: &'a str, current: &'a mut String) -> TokenList<'a> {
let out = TokenList::<'a>::new();
out.push(current.as_str());
out.push(ch);
*current = String::new();
out
}
通过这种方式,您会将out
的所有权传递给调用方,并且它将存在足够长的时间.
This way you will pass the ownership of out
to the caller and it will live long enough.
这篇关于延长锈蚀寿命的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!