【问题标题】:Lifetimes in Rust when using Strings使用字符串时 Rust 中的生命周期
【发布时间】:2020-04-20 10:56:04
【问题描述】:

我已经在 Rust 上进行了一段时间的试验。 Rust 中的生命周期存在一些混淆。请看下面的代码:

    fn main() {
    let string1 = String::from("abcd");
    let result;
    {
    let string2 = "xyzvn";

    result = longest(string1.as_str(),string2);

    }
    println!("The Longest String is {}",result);
}

fn longest<'a>(x: &'a str,y:&'a str) -> &'a str{
    if x.len() >y.len(){
        x
    }
    else{
        y
    }
}

string2 的生命周期在内部作用域之后结束,结果在外部作用域中定义。当在 println! 中传递结果时,编译不会报错,继续打印结果。 但是,当我将 string2 更改为:

let string2 = String::from("xyzvd");

借用检查器会抱怨。为什么会这样。

【问题讨论】:

    标签: rust


    【解决方案1】:

    字符串文字”xyzvn” 的类型是&amp;'static str,这意味着它与程序一样长。但是,当您基于它创建一个新字符串时,它的生命周期将在块的末尾结束,并且不能在外部使用。

    欲了解更多信息,请参阅documentation on static lifetime

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-03
      • 2022-12-13
      • 2014-12-29
      • 2012-04-15
      • 2015-01-22
      • 2017-05-03
      • 1970-01-01
      相关资源
      最近更新 更多