String 字符串';返回Vec时的s生存期<&;str>;
简单代码:String 字符串';返回Vec时的s生存期<&;str>;,string,vector,rust,lifetime,String,Vector,Rust,Lifetime,简单代码: 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 e
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
}
fn foo()->VecA&'static str
是字符串文本,例如让A:&'static str=“hello world”
。它存在于应用程序的整个生命周期中
如果要创建新的字符串
,则该字符串不是静态的
只需返回字符串的向量
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();
}
fn foo()->Vec{
让mut-vec=vec::new();
让mut string=string::new();
//用绳子做某事。。。
矢量推力(弦);
返回向量;
}
fn main(){
foo();
}
您好,谢谢,将字符串更改为str很有帮助,所以str的方法与String相同?我说得对吗?@RišoBaláž,这更像是String
与str
有着相同的方法,因为String
有一个Deref
实现。请参见(底部)和。按照习惯用法,您不会使用return vec
,只需使用vec
结束该方法即可。