返回 Vec<&str> 时字符串的生命周期 [重复]

2023-12-06

简单代码:

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
}

我有问题,我需要用字符串处理并将其返回Vec作为海峡问题是绑定字符串的寿命不够长,因为它在 foo 之后超出了范围。我很困惑,我真的不知道如何解决这个问题。


A &'static str是一个字符串文字,例如let a : &'static str = "hello world"。它存在于应用程序的整个生命周期中。

如果您正在创建一个新的String,那么该字符串不是静态的!

只需返回一个向量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();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

返回 Vec<&str> 时字符串的生命周期 [重复] 的相关文章

随机推荐