微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Rust 中的生命周期如何为函数工作?

如何解决Rust 中的生命周期如何为函数工作?

lifetime_things的定义中,'b的生命周期比'a长,但实际上我调用这个函数时,x1比{{1}长},但这可以成功编译:

y1

但是在这里你可以看到 //here you Could see 'b:'a means,the lifetime of b should be larger than a,fn lifetime_things<'a,'b:'a>(x:&'a String,y:&'b String) ->&'a String { if x.len() > y.len() { &x } else { &y } } fn main() { let z: i32; let x = String::from("1"); let x1=&x; { let y = String::from("2"); let y1=&y; println!("{}",lifetime_things(x1,y1)); } } 的生命周期应该大于 x1 那么为什么它也能成功编译?

解决方法

'b: 'a 意味着 'b 必须比 'a 存活,这反过来意味着只要 'a 处于存活状态,'b 也必须存活。至关重要的是,这是一个大于或等于的关系。还要注意生命周期不像类型那样工作。当函数接受 'v 引用时,只要 'w,任何生命周期 ('w: 'v) 都将被接受。

那么,'a 在哪里直播?在函数体中以及在调用后使用返回的字符串引用时。我们可以这样想象它:

fn lifetime_things<'a,'b:'a>(x:&'a String,y:&'b String) ->&'a String {
  if x.len() > y.len() {                         // <-+
    &x                                           //   |
  } else {                                       //   |
    &y                                           //   +----+
  }                                              //   |    |
}                                                // <-+    |
                                                 //        |
fn main() {                                      //        +-- 'a
let z: i32;                                      //        |
    let x = String::from("1");                   //        |
    let x1=&x;                                   //        |
    {                                            //        |
        let y = String::from("2");               //        |
        let y1=&y;                               //        |
        println!("{}",lifetime_things(x1,y1));   // <------+
    }
}

请注意,由于 lifetime_things 返回的值仅被打印,因此 'a 仅存在于 println!("{}",y1)); 行(不包括 lifetime_things 的正文)。

因此,要调用 lifetime_things,我们只需要至少在调用时使用这两个参数。这对 x1y1 均成立,因此全部检查完毕。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。