返回Vec< str>时String的生存期. [英] String's lifetime when returning Vec<&str>
本文介绍了返回Vec< str>时String的生存期.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
简单代码:
fn foo() -> Vec<&'static str> {
let mut vec = Vec::new();
let mut string = String::new();
// doing something with string...
vec.push(string.as_str());
return vector; // error here: string doesn't live long enough
}
我有一个问题,我需要处理字符串并将其作为str返回到Vec
中.问题在于绑定字符串的生存期不够长,因为它在foo之后超出范围.我很困惑,我真的不知道该如何解决.
I have problem that I need to process with string and return it in Vec
as str. Problem is that binding string doesn't live long enough, since it goes out of scope after foo. I am confused and I don't really know how to solve that.
推荐答案
&'static str
是字符串文字,例如let a : &'static str = "hello world"
.它存在于应用程序的整个生命周期中.
A &'static str
is a string literal e.g. let a : &'static str = "hello world"
. It exists throughout the lifetime of the application.
如果要创建新的String
,则该字符串不是静态的!
If you're creating a new String
, then that string is not static!
简单地返回String
的向量.
fn foo() -> Vec<String> {
let mut vec = Vec::new();
let mut string = String::new();
// doing something with string...
vec.push(string);
return vec;
}
fn main() {
foo();
}
这篇关于返回Vec< str>时String的生存期.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文