简体   繁体   English

使用字符串时 Rust 的生命周期

[英]Lifetimes in Rust when using Strings

I have been experimenting on Rust for quite some time.我已经在 Rust 上试验了一段时间。 There is a confusion regarding the lifetimes in Rust.Have a look in the code below:关于 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
    }
}

The string2 lifetime ends after the inner scope, and result is defined in the outer scope.When passing result in println!, the compile does not complain, and goes ahead and prints the result. string2 生命周期在内部作用域之后结束,结果在外部作用域中定义。在 println! 中传递结果时,编译不会报错,继续打印结果。 However when I change the string2 to be like:但是,当我将 string2 更改为:

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

The borrow checker will complain.借阅检查员会抱怨。 Why is that happening.为什么会这样。

The type for a string literal ”xyzvn” is &'static str which means it lives as long as the program does.字符串文字”xyzvn”的类型是&'static str ,这意味着它的生命”xyzvn” &'static str程序一样长。 But when you create a new string based on it its lifetime ends at the end of the block and it cannot be used outside.但是当您基于它创建一个新字符串时,它的生命周期在块的末尾结束,并且不能在外部使用。

For more information see the documentation on static lifetime有关更多信息,请参阅有关静态生命周期文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM