其他分享
首页 > 其他分享> > [易学易懂系列|rustlang语言|零基础|快速入门|(5)|生命周期Lifetime]

[易学易懂系列|rustlang语言|零基础|快速入门|(5)|生命周期Lifetime]

作者:互联网

[易学易懂系列|rustlang语言|零基础|快速入门|(5)]

Lifetimes

我们继续谈谈生命周期(lifttime),我们还是拿代码来说话:


fn main() {
  let mut a = vec![1, 2, 3];
  let b = &mut a;  //  &mut borrow of `a` starts here
  // some code

  println!("{:?}", a); // trying to access `a` as a shared borrow, so giving an error
}                  //  &mut borrow of `a` ends here

我们在上篇文章说到,这段代码:


println!("{:?}", a);

是过不了霸道的编译器女王的检查的?

为什么?

因为b借用了a的数据所有权,没有还回来。

所以,这时,访问a的数据时,编译器女王报错。

那要怎么办?加大括号 {}。

如下 :


fn main() {
  let mut a = vec![1, 2, 3];
  {
    let b = &mut a;  //  &mut borrow of `a` starts here
    // any other code
  }                  //  &mut borrow of `a` ends here

  println!("{:?}", a); // allow borrowing `a` as a shared borrow
}

我们可以看到,b 的“生命周期”,是限定在大括号 {}中的。

我们来看一个更清楚的代码:



我们现在知道,可以用大括号来限定变量或引用的生命周期。但太多大括号,会让你看得头大。

点击查看源网页

没关系,rust都为你考虑到了。下面是生命周期定义的标准写法。

翠花,上代码 :



// No inputs, return a reference
fn function<'a>() -> &'a str {}

// Single input
fn function<'a>(x: &'a str) {}

// Single input and output, both have the same lifetime
// The output should live at least as long as input exists
fn function<'a>(x: &'a str) -> &'a str {}

// Multiple inputs, only one input and the output share same lifetime
// The output should live at least as long as y exists
fn function<'a>(x: i32, y: &'a str) -> &'a str {}

// Multiple inputs, both inputs and the output share same lifetime
// The output should live at least as long as x and y exist
fn function<'a>(x: &'a str, y: &'a str) -> &'a str {}

// Multiple inputs, inputs can have different lifetimes 

标签:function,mut,生命周期,Struct,rustlang,str,易懂,Lifetime,fn
来源: https://www.cnblogs.com/gyc567/p/12045378.html