首页 技术 正文
技术 2022年11月19日
0 收藏 623 点赞 2,819 浏览 1194 个字

[易学易懂系列|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

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,103
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,579
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,427
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,199
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,834
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,917